首页 > 解决方案 > 如何在 asdict 中获取@property 方法?

问题描述

我有类似的东西:

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}.

实现上述目标的最干净方法是什么?

标签: pythonpython-attrs

解决方案


通常,您必须遍历属性并检查实例,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'}

推荐阅读