【问题标题】:Get all @properties from a Python Class [duplicate]从 Python 类中获取所有 @properties [重复]
【发布时间】:2021-04-25 17:34:46
【问题描述】:

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

【问题讨论】:

    标签: python properties code-inspection


    【解决方案1】:

    我们可以通过使用cls.__dict__ 获得类cls 的所有属性。由于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)
        ]
    

    【讨论】:

    • 这不会找到继承的属性。你需要遍历整个 MRO。
    • @user2357112supportsMonica 好点。感谢您的提示。 stackoverflow.com/questions/5876049/… 的答案中也缺少这一点,所以我在那里发布了答案。
    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多