我有类似的东西:
from attr import attrs, attrib
@attrs
class Foo():
max_count = attrib()
@property
def get_max_plus_one(self):
return self.max_count + 1
现在当我这样做时:
f = Foo(max_count=2)
f.get_max_plus_one =>3
我想将其转换为字典:
{'max_count':2, 'get_max_plus_one': 3}
当我使用attr.asdict(f)
我不明白@property
。我只得到{'max_count':2}
.
实现上述目标的最干净的方法是什么?
一般来说,您必须迭代classes属性并检查实例property
然后调用属性__get__
使用实例的方法。所以,像这样:
In [16]: class A:
...: @property
...: def x(self):
...: return 42
...: @property
...: def y(self):
...: return 'foo'
...:
In [17]: a = A()
In [18]: vars(a)
Out[18]: {}
In [19]: a.x
Out[19]: 42
In [20]: a.y
Out[20]: 'foo'
In [21]: {n:p.__get__(a) for n, p in vars(A).items() if isinstance(p, property)}
Out[21]: {'x': 42, 'y': 'foo'}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)