Open In App

Dynamic Attributes in Python

Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for better understanding about the topic.

Example 1:




class GFG:
    None
      
def value():
    return 10
  
# Driver Code
g = GFG()
  
# Dynamic attribute of a
# class object
g.d1 = value
  
# Dynamic attribute of a 
# function
value.d1 = "Geeks"
  
print(value.d1)
print(g.d1() == value())

Output:

Geeks
True

Now, the above program seems to be confusing, but let’s try to understand it. Firstly let’s see the objects, g and value(functions are also considered as objects in Python) are the two objects. Here the dynamic attribute for both the objects is “d1”. This is defined at runtime and not at compile time like static attributes.

Note: The class “GFG” and all other objects or instances of this class do not know the attribute “d1”. It is only defined for the instance “g”.

Example 2:




class GFG:
      
    employee = True
  
# Driver Code
e1 = GFG()
e2 = GFG()
  
e1.employee = False
e2.name = "Nikhil"
  
print(e1.employee)
print(e2.employee)
print(e2.name)
  
# this will raise an error 
# as name is a dynamic attribute
# created only for the e2 object
print(e1.name)

Output:

False
True
Nikhil
Traceback (most recent call last):
  File "/home/fbcfcf668619b24bb8ace68e3c400bc6.py", line 19, in 
    print(e1.name)
AttributeError: 'GFG' object has no attribute 'name'

Article Tags :