问题
In Python, how can I get all properties of a class, i.e. all members created by the @property
decorator?
There are at least two questions[1, 2] on stackoverflow which confound the terms property and attribute, falsely taking property as a synonym for attribute, which is misleading in Python context. So, even though the other questions' titles might suggest it, they do not answer my question.
[1]: Print all properties of a Python Class
[2]: Is there a built-in function to print all the current properties and values of an object?
回答1:
We can get all attributes of a class cls
by using cls.__dict__
. Since property
is a certain class itself, we can check which attributes of cls
are an instance of property
:
from typing import List
def properties(cls: type) -> List[str]:
return [
key
for key, value in cls.__dict__.items()
if isinstance(value, property)
]
来源:https://stackoverflow.com/questions/65825035/get-all-properties-from-a-python-class