我想知道使以下数据类 bar
卡住的任何简单方法。
@dataclass
class Bar:
foo: int
bar = Bar(foo=1)
换句话说,我想要下面的函数
some_fn_to_freeze
frozen_bar = some_fn_to_freeze(bar)
frozen_bar.foo = 2 # Error
并且,反函数
some_fn_to_unfreeze
bar = som_fn_to_unfrozen(frozen_bar)
bar.foo = 3 # not Error
最佳答案
Python 数据类很棒,但 attrs 包是一个更灵活的替代方案,如果您能够使用第三方库。例如:
import attr
# Your class of interest.
@attr.s()
class Bar(object):
val = attr.ib()
# A frozen variant of it.
@attr.s(frozen = True)
class FrozenBar(Bar):
pass
# Three instances:
# - Bar.
# - FrozenBar based on that Bar.
# - Bar based on that FrozenBar.
b1 = Bar(123)
fb = FrozenBar(**attr.asdict(b1))
b2 = Bar(**attr.asdict(fb))
# We can modify the Bar instances.
b1.val = 777
b2.val = 888
# Check current vals.
for x in (b1, fb, b2):
print(x)
# But we cannot modify the FrozenBar instance.
try:
fb.val = 999
except attr.exceptions.FrozenInstanceError:
print(fb, 'unchanged')
输出:
Bar(val=888)
FrozenBar(val=123)
Bar(val=999)
FrozenBar(val=123) unchanged
关于python - 如何使非卡住数据类卡住,反之亦然?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56069359/