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
g = GFG()
g.d1 = value
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
e1 = GFG()
e2 = GFG()
e1.employee = False
e2.name = "Nikhil"
print (e1.employee)
print (e2.employee)
print (e2.name)
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'
Last Updated :
26 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...