Get all @properties from a Python Class [duplicate]

痴心易碎 提交于 2021-01-28 21:34:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!