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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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())

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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'



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.