[英]How to get @property methods in asdict?
I have something like:我有类似的东西:
from attr import attrs, attrib
@attrs
class Foo():
max_count = attrib()
@property
def get_max_plus_one(self):
return self.max_count + 1
Now when I do:现在当我这样做时:
f = Foo(max_count=2)
f.get_max_plus_one =>3
I want to convert this to dict:我想将其转换为 dict:
{'max_count':2, 'get_max_plus_one': 3}
When I used attr.asdict(f)
I do not get the @property
.当我用
attr.asdict(f)
我没有得到@property
。 I get only {'max_count':2}
.我只得到
{'max_count':2}
。
What is the cleanest way to achieve the above?实现上述目标的最干净方法是什么?
In general, you would have to iterate over the classes attributes and check for instances of property
and then call the properties __get__
method using the instance.在一般情况下,你将不得不遍历类的属性和检查的情况下,
property
,然后调用属性__get__
使用实例方法。 So, something like:所以,像这样:
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'}
For this case, you can use dir
on the object, and get only the properties that do not start with __
ie ignore the magic methods:对于这种情况,您可以在对象上使用
dir
,并仅获取不以__
开头的属性,即忽略魔术方法:
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}
To handle the regular methods that do not start with __
, you can add a callable
test:要处理不以
__
开头的常规方法,您可以添加一个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}
I'm afraid that isn't supported by attrs
at the moment.恐怕目前
attrs
不支持。 You may want to follow/comment on https://github.com/python-attrs/attrs/issues/353 which may give you what you want eventually.您可能想在https://github.com/python-attrs/attrs/issues/353上关注/评论,这可能最终会为您提供您想要的东西。
If you define:如果你定义:
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
Then you get what you were looking for:然后你会得到你想要的:
>>> attr2dict(f)
{'max_count': 2, 'get_max_plus_one': 3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.