Home > Article > Backend Development > How to Dynamically Add Properties to a Python Class?
How to Dynamically Add Properties to a Class
In Python, it's possible to create instance properties dynamically, giving you the flexibility to modify the behavior of a class during runtime. Here's how it's done:
The first approach you attempted was incorrect, as it set c.ab to a property object instead of the actual value. To correctly add a property, you need to modify the class itself, not the instance.
class C(dict): pass ks = ['ab', 'cd'] vs = [100, 200] for i, k in enumerate(ks): # Define the property using classmethod setattr(C, k, property(lambda self: vs[i])) c = C() print(c.ab) # Outputs 100
In this updated code, we define the setattr call as a classmethod, which ensures that the property is added to the class rather than the instance. The lambda function within the property returns the corresponding value from the vs list.
Properties can also be used to define dynamic getter and setter functions, providing greater flexibility in property handling. Remember, property addition can only be done on the class level, not the instance level, making it a powerful tool for customizing class behavior.
The above is the detailed content of How to Dynamically Add Properties to a Python Class?. For more information, please follow other related articles on the PHP Chinese website!