Introduction
The attributes or methods of a class are the properties of that class. The attributes are non-callable properties and similarly, methods are the callable properties for a function. There are many concepts are introduced in Python in order to improve the concept of utilizing attributes and methods. For example, introducing the concept of access specifiers to make the attributes and properties securely accessible within or among the classes. Similarly, the concept of dynamicity is introduced for attributes and properties so as to dynamically access and use attributes and properties of a particular class. We will go through the concept of dynamic attributes and properties in python in this article.
Also Read, Divmod in Python, Swapcase in Python
Dynamic Attributes and properties in Python
The concept of dynamic attributes is introduced because of a need that static attributes don’t provide. Let’s say we have a class like this:
class Sample:
#static attribute
Static_attribute = 1
a = Sample()
a.Static_attribute = 2
#dynamic attribute or instance attribute
a.dynamic_attribute = 2
print(a.Static_attribute)
print(a.dynamic_attribute)
Output:
2
2
We can see that the attribute “dynamic_attribute” is a dynamic attribute because it is created and used after an object or instance is created, i.e., fairly at runtime. These attributes are called dynamic attributes. We can conclude that the attributes that are declared at runtime or after an object or instance is created are called dynamic attributes.
Let’s take another example,
class Sample:
pass
x = Sample()
y = Sample()
x.var1 = 2
x.var2 = 3
y.var1 = 5
print(x.var1)
print(x.var2)
print(y.var1)
print(y.var2)
Output:
2
3
5
Error, because the object var2 isn’t yet defined for y object.
This var2 is only defined dynamically for the object x. In this way, these dynamic attributes can work. This concept also involves making the objects or instances secured.
We can add properties to the class dynamically using the self.__dict__[key] = value
In the key, we have to pass the attribute or property name and the value to the value of that property. You can practice by yourself with the help of online python compiler for better understanding.
Want to know about Fibonacci Series in Python and Convert String to List Python check this out.