从 Python 类中获取所有 @properties

在 Python 中,如何获取类的所有属性,即由 @property 装饰器创建的所有成员?

stackoverflow 上至少有两个问题[1,2]混淆了术语propertyattribute,错误地采用了 property 作为 attribute 的同义词,在 Python 上下文中会产生误导。因此,即使其他问题的标题可能暗示了这一点,但它们并没有回答我的问题。


[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?

aidetianshi123456 回答:从 Python 类中获取所有 @properties

我们可以使用 cls 获取类 cls.__dict__ 的所有属性。由于 property 本身就是某个类,我们可以检查 cls 的哪些属性是 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://www.f2er.com/1066810.html

大家都在问