Home > Article > Backend Development > How to Add Dynamic Properties to Classes like Dictionary Entries?
Adding Dynamic Properties to Classes
In the quest to simulate a database result set using mock classes, a challenge arises: how to assign dynamic properties to an instance that resemble those of a dictionary. This involves creating properties that behave like attributes with specific values.
Initially, a promising approach involved assigning properties using:
setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))
However, this yielded property objects instead of the desired behavior.
The solution lies in adding properties to the class itself, rather than individual instances. Here's how it works:
class Foo(object): pass foo = Foo() foo.a = 3 Foo.b = property(lambda self: self.a + 1) print(foo.b) # Prints 4
In this example, we add a property b to the class Foo using the property descriptor. When accessing foo.b, Python calls the __get__ method of the descriptor and passes the class instance as an argument. The __get__ method then returns the value of the property, which is calculated as self.a 1.
Properties provide a convenient way to define custom behavior for attributes, effectively exposing the plumbing of Python's OO system.
The above is the detailed content of How to Add Dynamic Properties to Classes like Dictionary Entries?. For more information, please follow other related articles on the PHP Chinese website!