Home > Backend Development > Python Tutorial > How to Add Dynamic Properties to Classes like Dictionary Entries?

How to Add Dynamic Properties to Classes like Dictionary Entries?

Linda Hamilton
Release: 2024-11-12 10:55:03
Original
776 people have browsed it

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))
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template