繁体   English   中英

获取 python 中 class 的“属性”class 属性列表

[英]Get the list of 'property' class attributes of a class in python

亲爱的 Stackoverflow 社区,

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

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 )。 我错过了什么?

谢谢!

property是在 class 上定义的,如果您尝试通过实例访问它们,则会调用它们的__get__ 因此,改为使用 class 方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM