0% found this document useful (0 votes)
46 views

Example Program With Both Class Attributes and Instance Attributes

The document describes class and instance attributes in Python classes. It defines an Employee class with a class attribute empCount to track the number of employees and instance attributes like name and salary for each employee object. Methods like __init__() and empdetails() are used to initialize objects and display their details. The class and instance attributes allow storing and accessing shared and unique data respectively for the class and its objects.

Uploaded by

Prameela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Example Program With Both Class Attributes and Instance Attributes

The document describes class and instance attributes in Python classes. It defines an Employee class with a class attribute empCount to track the number of employees and instance attributes like name and salary for each employee object. Methods like __init__() and empdetails() are used to initialize objects and display their details. The class and instance attributes allow storing and accessing shared and unique data respectively for the class and its objects.

Uploaded by

Prameela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Example Program with both class attributes and instance attributes

class Employee:
'A Class of Employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

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()

 A class Employee with a class attribute named empCount and instance


attributes name and salary. Class methods empcount and empdetails to
display the total number of employees and their details respectively
 The variable empCount is a class variable whose value is shared among all
instances of this class. This can be accessed as Employee.empCount from
inside the class or outside the class.
 The first method __init__() is a special method, which is called class
constructor or initialization method that Python calls when we create a new
instance of this class.
 We declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to
the list for us; we need not include it when we call the methods.
 Emp1 and emp2 are the two objects of Class Employee.
 The method empdetails is accessed by the object1 and object2 to display its
details.
 Total number of employees can be printed by the object1 or object2 by
accessing the method empcount(), which gives the same value
class Employee:
'A Class of Employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

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 __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def empdetails(self):
print ("Name : "+ self.name , “Salary: %d" +self.salary)

print ("Total number of Employees are "+ Employee.empCount)


emp1=Employee(“Mivaan”,400000000)
emp2=Employee(“Haarika”,40000000)
emp1.empdetails()
emp2.empdetails()
emp1.age=7
emp1.empdetails()--------Only emp1 gets a new attribute
emp2.empdetails()--------emp2 remains unchanged
emp1.age=8
emp1.empdetails()
del emp1.age
emp1.empdetails()
In this example only the instance emp1 is added with a new attribute age,
modified and deleted… It is not applicable to emp2. This can be observed by
comparing the two outputs.

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 __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def empdetails(self):
print ("Name : ", self.name , “Salary:", self.salary)

print ("Total number of Employees are ", Employee.empCount)


emp1=Employee(“Mivaan”,400000000)
emp2=Employee(“Haarika”,40000000)
emp1.empdetails()
emp2.empdetails()
setattr(emp1, ‘age’,8)--- creates a new attribute age and sets its value to 8
emp1.empdetails()
hasattr(emp1, ‘age’)---- returns True
getattr(emp1, ‘age’)---- returns the value of age as 8
delattr(emp1, ‘age’)---- deletes the instance attribute age
emp1.empdetails()

Built-In Class Attributes

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 __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def empdetails(self):
print ("Name : ", self.name , “Salary: ", self.salary)

print ("Total number of Employees are ", Employee.empCount)


emp1=Employee(“Mivaan”,400000000)
emp2=Employee(“Haarika”,40000000)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print( "Employee.__dict__:", Employee.__dict__)

Destroying Objects (Garbage Collection)

Python deletes unneeded objects (built-in types or class instances)


automatically to free the memory space. The process by which Python
periodically reclaims blocks of memory that no longer are in use is termed
Garbage Collection.
Python's garbage collector runs during program execution and is triggered
when an object's reference count reaches zero. An object's reference count
changes as the number of aliases that point to it changes.
An object's reference count increases when it is assigned a new name or placed
in a container (list, tuple, or dictionary). The object's reference count decreases
when it's deleted with del, its reference is reassigned, or its reference goes out
of scope. When an object's reference count reaches zero, Python collects it
automatically.
a = 20 # Create object <40>
b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
We normally will not notice when the garbage collector destroys an orphaned
instance and reclaims its space. But a class can implement the special
method __del__(), called a destructor, that is invoked when the instance is about
to be destroyed. This method might be used to clean up any non memory
resources used by an instance.

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

You might also like