简体   繁体   English

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

[英]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.

相关问题 如何获得所有用@property装饰的方法的列表? - How to get a list of all methods decorated with `@property`? 如何覆盖 Python Dataclass 'asdict' 方法 - How to overwrite Python Dataclass 'asdict' method 数据类:如何使用 asdict() 忽略 None 值? - dataclasses: how to ignore None values using asdict()? 如何在数据类 asdict() output 中包含 ClassVars? - How to include ClassVars in dataclass asdict() output? 如何在数据类模块的 asdict function 中使用枚举值 - How to use enum value in asdict function from dataclasses module 我如何模拟 Pytest 和 MagicMock 中 sqlalchemy 行的 _asdict() 方法? - How do i mock _asdict() method for sqlalchemy row in Pytest and MagicMock? python inspect get方法用@property修饰 - python inspect get methods decorated with @property Python 获取和设置方法与@property 装饰器 - Python get and set methods versus @property decorator 如何使用 Python 模块“attrs”实现“attr.asdict(MyObject)”的逆向 - How to achieve the reverse of "attr.asdict(MyObject)" using Python module 'attrs' 如何为 Python 中的 Apache Beam 制作有用的侧面输入? AsDict object 不可下标? - How do I make a useful side input I can access for Apache Beam in Python? AsDict object not subscriptable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM