【问题标题】:Get the list of 'property' class attributes of a class in python获取python中类的“属性”类属性列表
【发布时间】:2021-03-26 01:09:49
【问题描述】:

尊敬的 Stackoverflow 社区,

我正在尝试获取班级中的属性列表。到目前为止,我有这个:

class A(object):

    def __init__(self):
        self._val = 0

    @property
    def val(self):
        return self._val

    @val.setter
    def val(self, val):
        """
        +1 just as a lazy check if the method is invoked
        """
        self._val = val + 1

    def get_props(self):
        return [ str(x) for x in dir(self)
                if isinstance( getattr(self, x), property ) ]

if __name__ == "__main__":

    import sys

    print("Python version")
    print (sys.version)
    print("Version info.")
    print (sys.version_info)
    print()

    a = A()
    print(f"Before asigment: {a.val}")
    a.val = 19
    print(f"After asigment: {a.val}")
    print(f"My properties: {a.get_props()}")
    print(f"The type of the attribute 'val' is {type(getattr(a, 'val'))}")

根据this Q/A,它应该可以工作。但是,我的结果是:

Python version
3.7.3 (default, Jul 25 2020, 13:03:44) 
[GCC 8.3.0]
Version info.
sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)

Before asigment: 0
After asigment: 20
My properties: []
The type of the attribute 'val' is <class 'int'>

我试图避免导入新模块(如 inspect)。我错过了什么?

谢谢!

【问题讨论】:

  • 你应该使用vars(x).items()) 而不是dir(x)

标签: python class properties


【解决方案1】:

propertys 是在类上定义的,如果您尝试通过实例访问它们,则会调用它们的 __get__。所以让它成为一个类方法:

    @classmethod
    def get_props(cls):
        return [x for x in dir(cls)
                if isinstance( getattr(cls, x), property) ]

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2020-02-29
    相关资源
    最近更新 更多