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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3