Dynamic Attributes in Python
If the attribute of an instance is defined after creating an instance then the attribute is known as Dynamic Attribute. Everything in Python is an object. Even functions and methods are also an object. So the dynamic attribute defines anything in Python.
Let us understand this using an example:
Example1 :
Look at the Python code below:
# Python Program of Dynamic Attribute class CodeSpeedy: None def get_val(): return 0 # instance of the class x = CodeSpeedy() # Dynamic attribute of a class instance x.dy = get_val # Function is also an object in python # Dynamic attribute of a function get_val.dy = 'CodeSpeedy' print(get_val.dy)
Output:
CodeSpeedy
In the above example, there is a class ‘CodeSpeedy’. As mentioned above, everything in python is just an object. So here are two instances of CodeSpeedy class, one is ‘x’ and the other is get_val. The ‘dy’ is the dynamic attribute of both the instance of the class as well as the function get_val(). As defined after creating the instance i.e. at runtime that’s why it is a ‘Dynamic Attribute’.
Example2:
Only the instance can access the dynamic attribute for which it is defined. It cannot associate with the other instances of the class.
# Python Program for Dynamic attributes. class CodeSpeedy: None # Driver Code # two different objects are created obj1 = CodeSpeedy() obj2 = CodeSpeedy() # dynamic attributes for both the object. obj1.dy1 = 'Code' obj2.dy2 = 'Speedy' print(obj1.dy1) print(obj2.dy2) # it will generate an error print(obj1.dy2)
Output:
In the above example, obj1 and obj2 are the two objects of the class ‘CodeSpeedy’. Here dy1 and dy2 are the two dynamic attributes of instances obj1 and obj2. We have defined the dynamic attributes for specifically each of the instances. The dy2 is only created for instance obj2, so it will raise an error when dy2 associates with other instances like an error occur while associating dy2 with obj1 since dy2 is limited for only obj2.
Leave a Reply