在Python模块attrs
stated的documentation中,有一种将属性类转换为字典表示的方法:
示例:
>>> @attr.s
... class Coordinates(object):
... x = attr.ib()
... y = attr.ib()
...
>>> attr.asdict(Coordinates(x=1, y=2))
{'x': 1, 'y': 2}
我如何实现oposite:从其有效的字典表示中获取Coordinates
的实例,而不需要样板,并且可以享受attrs
模块的乐趣?在
作为一个更通用的解决方案,它与attrs嵌套类、枚举或任何其他类型注释结构一起工作,您可以使用https://github.com/Tinche/cattrs
示例:
我在我的web应用程序中这样做是为了能够序列化/反序列化为JSON:
首先,我在类上创建了一个方法,它返回一个更易于序列化的版本:
然后,当我需要将其中一个字典(实际上是JSON对象)转换回类实例时:
^{pr2}$显然与在相应的
attrs
类实例化中使用字典解包(double star)运算符一样简单。在示例:
相关问题 更多 >
编程相关推荐