Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Creating Instance Objects
When you create an object, Python calls the class constructor (__init__ method) to initialize the new instance ?
# This would create first object of Employee class
emp1 = Employee("Zara", 2000)
# This would create second object of Employee class
emp2 = Employee("Manni", 5000)
Accessing Object Attributes
You access the object's attributes using the dot (.) operator with object. Class variables can be accessed using class name ?
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)
Complete Example
Now, putting all the concepts together ?
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)
Name : Zara , Salary: 2000 Name : Manni , Salary: 5000 Total Employee 2
Modifying Object Attributes
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
Built-in Attribute Functions
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.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp1 = Employee("John", 3000)
print(hasattr(emp1, 'age')) # Returns True if 'age' attribute exists
setattr(emp1, 'age', 25) # Set attribute 'age' to 25
print(getattr(emp1, 'age')) # Returns value of 'age' attribute
delattr(emp1, 'age') # Delete attribute 'age'
False 25
Conclusion
Creating instance objects in Python involves calling the class constructor with required arguments. You can access and modify attributes using dot notation or built-in functions like getattr() and setattr().
