Python Classes and Objects
- Logically group data (attributes) and functions(methods)
- Class is like a design template
- Easy to reuse
- Easy to build upon (Upgrade or add more details i.e. attributes or methods)
Example: Employees would have specific attributes and methods. In an employee class, individual employee objects are called an instance of a class.
Class Creation
class employee:
Pass
Object Creation
employee1 = employee()
employee2 = employee()Both employees are the object of the class and have a separate memory
2 employee instance created for employee class.
Note: Employee class doesn’t have any attribute or methods at this stage
For the above employee class let us create attributes and methods
Incorrect Method:
employee1.name = ‘Raj’
employee1.age = 28employee1.name = ‘Alex’
employee1.age = 26
Define the attributes when defining the class and not when creating instances.
or
Inherit the parent class and add new attributes in the child class.
Correct Method:
class employee:
def __init__(self, name, age):
self.name = name
self.age = age
employee1= employee(‘Raj’, 28)
employee2 = employee(‘Alex’, 26)
Add methods to Class
Note: self automatically takes the object name.
def return_employee(self):
return ‘{}{}’.format(self.name, self.age)
print(employee1.return_employee())
print(employee2.return_employee())
or
call the class method using class name
print(employee.return_employee(employee1)
print(employee.return_employee(employee2)
Note – Each method inside the class can automatically take instance as 1st argument