Example Program With Both Class Attributes and Instance Attributes
Example Program With Both Class Attributes and Instance Attributes
class Employee:
'A Class of Employees'
empCount = 0
def empcount(self):
print ("Total number of Employees are %d", Employee.empCount)
def empdetails(self):
print ("Name : %s", self.name , “Salary: %d", self.salary)
emp1=Employee(“Mivaan”,400000000)
emp2=Employee(“Haarika”,40000000)
emp1.empdetails()
emp2.empdetails()
emp1.empcount()
def empdetails(self):
print ("Name : %s"+ self.name , “Salary: "+ self.salary)
emp1=Employee(“Mivaan”,400000000)
emp2=Employee(“Haarika”,40000000)
emp1.empdetails()
emp2.empdetails()
print ("Total number of Employees are" + Employee.empCount)
The second version of the same program where we don’t write a method to
print the total number of employees but simply write a print statement
separately.
We can add, remove, or modify attributes of classes and objects at any time
class Employee:
'A Class of Employees'
empCount = 0
def empdetails(self):
print ("Name : "+ self.name , “Salary: %d" +self.salary)
Instead of using the normal statements to access attributes, we can use the
following functions −
The getattr(obj, name) − to access the attribute of object.
The hasattr(obj,name) − to check if an attribute exists or not.
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then
it would be created.
The delattr(obj, name) − to delete an attribute.
class Employee:
'A Class of Employees'
empCount = 0
def empdetails(self):
print ("Name : ", self.name , “Salary:", self.salary)
Every Python class keeps following built-in attributes and they can
be accessed using dot operator like any other attribute −
__dict__ − Dictionary containing the class's namespace.
__doc__ − Class documentation string or none, if undefined.
__name__ − Class name.
__module__ − Module name in which the class is defined. This
attribute is "__main__" in interactive mode.
__bases__ − A possibly empty tuple containing the base classes, in
the order of their occurrence in the base class list.
class Employee:
'A Class of Employees'
empCount = 0
def empdetails(self):
print ("Name : ", self.name , “Salary: ", self.salary)
In this example __del__() destructor prints the class name of an instance that is
about to be destroyed .
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces the output in the following form.
Value differ from system to system
3083401324
3083401324
3083401324
Point destroyed