如何实现属性asdict(MyObject)“使用Python模块'attrs'

2024-10-01 11:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python模块attrsstateddocumentation中,有一种将属性类转换为字典表示的方法:

示例:

>>> @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模块的乐趣?在


Tags: 模块实例方法示例字典属性objectdocumentation
3条回答

作为一个更通用的解决方案,它与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')

我在我的web应用程序中这样做是为了能够序列化/反序列化为JSON:

首先,我在类上创建了一个方法,它返回一个更易于序列化的版本:

def asdict(self, serializable=True):
    if serializable:
        as_dict['type'] = self.__class__.__name__
        return as_dict
    else:
        return attr.asdict(self)

然后,当我需要将其中一个字典(实际上是JSON对象)转换回类实例时:

^{pr2}$

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

示例:

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

相关问题 更多 >