在 python 中获取类的'property'类属性列表



尊敬的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'))}")

根据这个问答,它应该起作用。然而,我的结果是:

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

谢谢!

propertys是在类上定义的,如果您试图通过实例访问它们,则会调用它们的__get__。因此,将其作为类方法:

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

最新更新