Classes and Objects in python
In this chapter you will learn about, Classes and Objects in python. In the previous chapters, we have studied the basics in the python. Now its time to jump more into the python, as we know the classes are the heart of any object-oriented programming languages.
How to create a class in python?
- We can create a class with the help of the keyword class.
- Then followed by the class name
- The name of the class should be in camel case
- Then followed by the colon
- Every class will have a special method called __init__
- The init method allows you to create an instance of the actual object
- You can pass n number of parameters to the init method
- The first param is self to the init method
- The self connects all the parameters to the self
- Afterwards, you can define any number of methods
Now let’s write an example for creating the class and accessing the method which is defined in the class
class Employee: def __init__(self, name, email): self.name = name self.email = email def greetEmployee(self): print("Good morning " + self.name) employeePerson = Employee("Stark", '') employeePerson.greetEmployee() # output # Good morning Stark
How to create an object of class?
Once we define the class and method inside the class, then we can create an object of the same class, an object is an instance of the class.
class Employee(): def __init__(self, name, email): self.name = name self.email = email def greetEmployee(self): print("Good morning " + self.name) employeePerson = Employee("Stark", '') employeePerson.greetEmployee() print(type(employeePerson)) # output # Good morning Stark # <class '__main__.Employee'>
As we can see in the above code snippet, the object employeePerson is an instance of a class Employee.
One thought on “Classes and Objects in python”
Comments are closed.