python - 如何使用Python模块 "attr.asdict(MyObject)"实现 'attrs'的反转

标签 python attributes python-attrs

documentation Python 模块 attrs stated有一种方法可以将属性的类转换为字典表示:

示例:

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

我如何实现相反的目标:从其有效的字典表示中获取 Coordinates 的实例,无需样板文件并享受 attrs 模块?

最佳答案

显然与在相应的 attrs 类实例化中使用字典解包 ( double star) 运算符一样简单。

示例:

>>> Coordinates(**{'x': 1, 'y': 2})
Coordinates(x=1, y=2)

关于python - 如何使用Python模块 "attr.asdict(MyObject)"实现 'attrs'的反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44801927/

相关文章:

java - Java中的@override和Python中的@decorator的区别

使用 attrs 对子类进行 Pycharm 类型提示

python - pip install mysqlclient 在 win64 上无法正常工作,出现错误 'Cannot open file: ' mysql.h'

Python 3.2 os 模块 - python 函数或 linux 命令?

python - 使用 Tensorflow/PyTorch 加速自定义函数的最小化

c# - C#泛型的属性限制

exception - GCC (ARM) 中异常处理程序的 __attribute__((interrupt))

c# - 是否可以使用属性来覆盖方法?

Python Attrs 在设置属性时触发转换器