Creating Instance Objects in Python


To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

You access the object's attributes using the dot (.) operator with object. Class variable would be accessed using class name as follows −

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Example

Now, putting all the concepts together −

 Live Demo

#!/usr/bin/python
class Employee:
   'Common base class for all employees'
   empCount = 0
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   def displayCount(self):
   print "Total Employee %d" % Employee.empCount
   def displayEmployee(self):
      print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Output

When the above code is executed, it produces the following result −

Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2

You can add, remove, or modify attributes of classes and objects at any time −

emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.

Instead of using the normal statements to access attributes, you can use the following functions −

  • The getattr(obj, name[, default]) − 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.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'

Learn more about Python Object-Oriented feature: Python Class & Objects Tutorial

Updated on: 29-Aug-2023

28K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements