显然,只需在相应的 attrs
类初始化中使用字典解包 (双星号) 运算符即可。
示例:
>>> Coordinates(**{'x': 1, 'y': 2})
Coordinates(x=1, y=2)
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对象)之一转换回类实例时:
obj_type = values.pop('type')
if obj_type in obj_list:
obj = getattr(sys.modules[__name__], obj_type)(**values)