Saturday 5 December 2015

Python: Class Vs Instance variables

Class variables are associated with class and available to all the instances (objects) of the class, where as instance variables are unique to objects, used to uniquely identify the object.

Employee.py
class Employee:
 """ Blue print for all employees """
 # Class level variables
 noOfEmployees=0
 organization="abcde corporation"
  
 def __init__(self, id=-1, firstName="Nil", lastName="Nil"):
  self.id = -1
  self.firstName = firstName
  self.lastName = lastName
  Employee.noOfEmployees+=1
  
 def displayEmployee(self):
  print(self.id, self.firstName, self.lastName)
  
emp1 = Employee(id=1, firstName="Hari Krishna", lastName="Gurram")
emp1.displayEmployee()
print("Total Employees : ", Employee.noOfEmployees)
print("Organization : ", Employee.organization)

emp2 = Employee(id=3, firstName="PTR")
emp2.displayEmployee()
print("Total Employees : ", Employee.noOfEmployees)
print("Organization : ", Employee.organization)

$ python3 Employee.py 
-1 Hari Krishna Gurram
Total Employees :  1
Organization :  abcde corporation
-1 PTR Nil
Total Employees :  2
Organization :  abcde corporation


As you observe Employee.py noOfEmployees, organization are class variables, are available to all the instances. Class variables are accessed using ClassName followed by dot followed by variable name.

Employee.noOfEmployees: is used to access class variable noOfEmployees.
Employee.organization: is used to access class variable organization.





Previous                                                 Next                                                 Home

No comments:

Post a Comment