我有一些类似的东西:
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
我想将其转换为dict:
{'max_count':2, 'get_max_plus_one': 3}
当我使用attr.asdict(f)
时,我得不到@property
。我只得到了{'max_count':2}
。
实现上述目标的最干净的方法是什么?
发布于 2018-08-08 14:17:57
恐怕attrs
目前还不支持这一点。你可能想在https://github.com/python-attrs/attrs/issues/353上关注/评论,它可能最终会给你想要的东西。
发布于 2021-01-25 21:21:22
如果您定义:
import attr
def attr2dict(inst):
dic = attr.asdict(inst)
dic.update({n: p.__get__(inst) for n, p in vars(type(inst)).items() if isinstance(p, property)})
return dic
然后你就会得到你想要的东西:
>>> attr2dict(f)
{'max_count': 2, 'get_max_plus_one': 3}
https://stackoverflow.com/questions/51733882
复制相似问题