如何使用Python模块“ attrs”实现“ attr.asdict(MyObject)”的反向转换

mis*_*ope 3 python attributes python-attrs

在Python模块的文档attrs 指出,有一种方法可以将属性的类转换为字典表示形式:

例:

>>> @attr.s
... class Coordinates(object):
...     x = attr.ib()
...     y = attr.ib()
...
>>> attr.asdict(Coordinates(x=1, y=2))
{'x': 1, 'y': 2}
Run Code Online (Sandbox Code Playgroud)

如何实现对立面:Coordinates从有效的字典表示形式中获取的实例,而不使用样板内容,并且对attrs模块感到满意?

mis*_*ope 7

显然与在相应的类实例中使用字典解包(双星)运算符一样容易attrs

例:

>>> Coordinates(**{'x': 1, 'y': 2})
Coordinates(x=1, y=2)
Run Code Online (Sandbox Code Playgroud)

  • 仅当您的班级是扁平的并且没有嵌套的复杂类型时,这才起作用。 (4认同)

Art*_*kov 5

作为更通用的解决方案,它适用于 attrs 嵌套类、枚举或任何其他类型的注释结构,您可以使用https://github.com/Tinche/cattrs

例子:

import attr, cattr

@attr.s(slots=True, frozen=True)  # It works with normal classes too.
class C:
        a = attr.ib()
        b = attr.ib()

instance = C(1, 'a')
cattr.unstructure(instance)
# {'a': 1, 'b': 'a'}
cattr.structure({'a': 1, 'b': 'a'}, C)
# C(a=1, b='a')
Run Code Online (Sandbox Code Playgroud)