Home >Backend Development >Python Tutorial >How Can I Dynamically Set Attributes in Python Objects?
Setting Attributes Dynamically in Python
Suppose you have a Python object x and a string s. How do you programmatically set the attribute s on x such that the attribute can be accessed as x.myAttr?
To accomplish this, you can utilize the setattr() built-in function, which has the following syntax:
setattr(object, name, value)
In this specific scenario, you would use it as follows:
setattr(x, attr, 'magic')
This effectively sets the attribute attr on the object x to the value 'magic'. As a result, you can now access this attribute through x.myAttr.
It's important to note that this approach can be particularly useful for caching calls to x.__getattr__(). Keep in mind, however, that you cannot directly apply this method to a pure instance of object. Instead, it is more commonly applied to custom subclasses of object.
The above is the detailed content of How Can I Dynamically Set Attributes in Python Objects?. For more information, please follow other related articles on the PHP Chinese website!