扩展不可变(冻结)数据类
Extend immutable (frozen) dataclasses
我发现使用冻结数据class 是 make Python objects immutable 最干净的解决方案。添加单个 class 装饰器的实现非常简单:
from dataclasses import dataclass
@dataclass(frozen=True)
class Immutable:
attr1: int
attr2: int
现在我想通过引入新属性 attr3
来扩展 Immutable
class:
class MyImmutableChild(Immutable):
attr3: int
但是,行为并不像预期的那样:
>>> immutable_obj = MyImmutableChild(attr1=1, attr2=3, attr3=5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-2b6c18366721> in <module>
----> 1 immutable_obj = MyImmutableChild(attr1=1, attr2=3, attr3=5)
TypeError: __init__() got an unexpected keyword argument 'attr3'
啊,给子class
再添加一个@dataclass(frozen=True)
装饰器就很简单了
我发现使用冻结数据class 是 make Python objects immutable 最干净的解决方案。添加单个 class 装饰器的实现非常简单:
from dataclasses import dataclass
@dataclass(frozen=True)
class Immutable:
attr1: int
attr2: int
现在我想通过引入新属性 attr3
来扩展 Immutable
class:
class MyImmutableChild(Immutable):
attr3: int
但是,行为并不像预期的那样:
>>> immutable_obj = MyImmutableChild(attr1=1, attr2=3, attr3=5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-2b6c18366721> in <module>
----> 1 immutable_obj = MyImmutableChild(attr1=1, attr2=3, attr3=5)
TypeError: __init__() got an unexpected keyword argument 'attr3'
啊,给子class
再添加一个@dataclass(frozen=True)
装饰器就很简单了