Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different. There are two ways to access the instance variable of class:
Example 1: Using Self and object referenceÂ
Python3
#creating classclass student:         # constructor    def __init__(self, name, rollno):                 # instance variable        self.name = name        self.rollno = rollno          def display(self):                 # using self to access        # variable inside class        print("hello my name is:", self.name)        print("my roll number is:", self.rollno)         # Driver Code# object createds = student('HARRY', 1001)Â
# function call through objects.display()Â
# accessing variable from# outside the classprint(s.name) |
Output:
hello my name is: HARRY my roll number is: 1001 HARRY
Time complexity: O(1) for both creating the class and calling the display() method and accessing the name variable outside the class.
Auxiliary space: O(1) as there are no additional data structures used and the memory space is constant.
Example 2: Using getattr()Â
Python3
# Python code for accessing attributes of classclass emp:    name='Harsh'    salary='25000'    def show(self):        print(self.name)        print(self.salary)         # Driver Codee1 = emp()# Use getattr instead of e1.nameprint(getattr(e1,'name'))   # returns true if object has attributeprint(hasattr(e1,'name'))   # sets an attribute setattr(e1,'height',152)   # returns the value of attribute name heightprint(getattr(e1,'height'))   # delete the attributedelattr(emp,'salary') |
Output:
Harsh True 152
