Different ways to access Instance Variable in Python
Last Updated :
27 Mar, 2024
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:
- Within the class by using self and object reference.
- Using getattr() method
Example 1: Using Self and object reference
Python3
class student:
def __init__( self , name, rollno):
self .name = name
self .rollno = rollno
def display( self ):
print ( "hello my name is:" , self .name)
print ( "my roll number is:" , self .rollno)
s = student( 'HARRY' , 1001 )
s.display()
print (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
class emp:
name = 'Harsh'
salary = '25000'
def show( self ):
print ( self .name)
print ( self .salary)
e1 = emp()
print ( getattr (e1, 'name' ))
print ( hasattr (e1, 'name' ))
setattr (e1, 'height' , 152 )
print ( getattr (e1, 'height' ))
delattr (emp, 'salary' )
|
Output:
Harsh
True
152
Share your thoughts in the comments
Please Login to comment...