- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Now, putting all the concepts together −
#!/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
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'
- How to create instance Objects using __init__ in Python?
- Creating anonymous objects in PHP
- Creating and Using Objects using Perl
- Creating multiple Java objects by one type only
- Class & Instance Attributes in Python
- Creating Classes in Python
- How to access Python objects within objects in Python?
- Creating Database Table in Python
- Timer objects in Python
- Barrier Objects in Python
- File Objects in Python?
- Python Code Objects
- Creating a Proxy Webserver in Python
- Inspect live objects in Python