如何使非冻结数据类冻结,反之亦然?

时间:2019-05-10 00:53:32

标签: python python-dataclasses

我想知道任何简单的方法来冻结以下数据类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

2 个答案:

答案 0 :(得分:2)

location.origin === 'https://example.com/pathname1/pathname2' location.href === 'https://example.com/pathname1/pathname2?queryParam1=1&queryParam2=2' location.pathname === '/pathname1/pathname2' location.search === '?queryParam1=1&queryParam2=2' 没有对此的内置支持。冻结状态是在整个类的基础上进行跟踪的,而不是在每个实例的基础上进行的,并且不支持自动生成冻结或未冻结的数据类等效项。

虽然您可以尝试做一些事来快速生成新的数据类,但它与dataclassisinstance以及您想要工作的其他东西的交互非常差。编写两个数据类和转换器方法可能更安全:

==

答案 1 :(得分:1)

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