如何在asdict中获取@property方法?

sup*_*kar 10 python python-attrs

我有类似的东西:

from attr import attrs, attrib

@attrs
class Foo():
    max_count = attrib()
    @property
    def get_max_plus_one(self):
         return self.max_count + 1
Run Code Online (Sandbox Code Playgroud)

现在当我这样做时:

f = Foo(max_count=2)
f.get_max_plus_one =>3
Run Code Online (Sandbox Code Playgroud)

我想将其转换为字典:

{'max_count':2, 'get_max_plus_one': 3}
Run Code Online (Sandbox Code Playgroud)

当我使用时,attr.asdict(f)我没有得到@property. 我只得到 {'max_count':2}.

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

hee*_*ayl 1

dir对于这种情况,您可以在对象上使用,并仅获取不以__ie 开头的属性,忽略魔术方法:

In [496]: class Foo():
     ...:     def __init__(self):
     ...:         self.max_count = 2
     ...:     @property
     ...:     def get_max_plus_one(self):
     ...:          return self.max_count + 1
     ...:     

In [497]: f = Foo()

In [498]: {prop: getattr(f, prop) for prop in dir(f) if not prop.startswith('__')}
Out[498]: {'get_max_plus_one': 3, 'max_count': 2}
Run Code Online (Sandbox Code Playgroud)

要处理不以 开头的常规方法__,您可以添加一个callable测试:

In [521]: class Foo():
     ...:     def __init__(self):
     ...:         self.max_count = 2
     ...:     @property
     ...:     def get_max_plus_one(self):
     ...:          return self.max_count + 1
     ...:     def spam(self):
     ...:         return 10
     ...:     

In [522]: f = Foo()

In [523]: {prop: getattr(f, prop) for prop in dir(f) if not (prop.startswith('__') or callable(getattr(Foo, prop, None)))}
Out[523]: {'get_max_plus_one': 3, 'max_count': 2}
Run Code Online (Sandbox Code Playgroud)