Saturday, 5 December 2015

Python: classes and objects

Class is a blue print to create objects.


Syntax
class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

‘class’ keyword is used to define a class. You can instantiate any number of objects from a class.

Syntax
objName = new ClassName(arguments)

test.py
class Employee:
 """ Employee class """
 noOfEmployees=0  # Class level variable
  
 def __init__(self, id, firstName, lastName):
  self.id = id
  self.firstName = firstName
  self.lastName = lastName
  Employee.noOfEmployees = Employee.noOfEmployees + 1
  
 def displayEmployee(self):
  print(self.id, self.firstName, self.lastName)
  
emp1 = Employee(1, "Hari Krishna", "Gurram")
print("Total Employees", Employee.noOfEmployees)

emp2 = Employee(2, "PTR", "Nayan")
print("Total Employees", Employee.noOfEmployees)

emp3 = Employee(3, "Sankalp", "Dubey")
print("Total Employees", Employee.noOfEmployees)

emp1.displayEmployee()
emp2.displayEmployee()
emp3.displayEmployee()

$ python3 test.py 
Total Employees 1
Total Employees 2
Total Employees 3
1 Hari Krishna Gurram
2 PTR Nayan
3 Sankalp Dubey


__init__(arguments)
__init__ is a special function called constructor used to initialize objects. In Employee class, __init__ method is used to initialize id, firstName, lastName to an object at the time of creation.

noOfEmployees=0
‘noOfEmployees’ is a class variable, shared by all the objects. Class variable are accessed using Class name like ClassName.variableName, ‘Employee.noOfEmployees’ is used to access the class variable noOfEmployees’.

Instance variables
Instance variables have values unique to an object. Usually these are defined in __init__ method. Employee class has 3 instance variables id, firstName, lastName.

The first parameter of any method in a class must be self. This parameter is required even if the function does not use it. ‘self’ is used to refer current object.




Previous                                                 Next                                                 Home

No comments:

Post a Comment