gpt4 book ai didi

python - 如何使数据类中的属性只读?

转载 作者:行者123 更新时间:2023-12-03 16:49:14 25 4
gpt4 key购买 nike

假设我有一个这样的类(class):

class C:

def __init__(self, stuff: int):
self._stuff = stuff

@property
def stuff(self) -> int:
return self._stuff

然后 stuff是只读的:
c = C(stuff=10)
print(c.stuff) # prints 10


c.stuff = 2

按预期失败

AttributeError: can't set attribute



如何使用数据类获得相同的行为?如果我也想拥有一个 setter , 我可以:
@dataclass
class DC:
stuff: int
_stuff: int = field(init=False, repr=False)

@property
def stuff(self) -> int:
return self._stuff

@stuff.setter
def stuff(self, stuff: int):
self._stuff = stuff

但是如果没有 @stuff.setter 我怎么能做到呢?部分?

最佳答案

获得样板减少dataclass我发现唯一的方法是使用描述符。

In [236]: from dataclasses import dataclass, field
In [237]: class SetOnce:
...: def __init__(self):
...: self.block_set = False
...: def __set_name__(self, owner, attr):
...: self.owner = owner.__name__
...: self.attr = attr
...: def __get__(self, instance, owner):
...: return getattr(instance, f"_{self.attr}")
...: def __set__(self, instance, value):
...: if not self.block_set:
...: self.block_set = True
...: setattr(instance, f"_{self.attr}", value)
...: else:
...: raise AttributeError(f"{self.owner}.{self.attr} cannot be set.")

In [239]: @dataclass
...: class Foo:
...: bar:str = field(default=SetOnce())

In [240]: test = Foo("bar")

In [241]: test.bar
Out[241]: 'bar'

In [242]: test.bar = 1
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-242-9cc7975cd08b> in <module>
----> 1 test.bar = 1

<ipython-input-237-bddce9441c9a> in __set__(self, instance, value)
12 self.value = value
13 else:
---> 14 raise AttributeError(f"{self.owner}.{self.attr} cannot be set.")
15

AttributeError: Foo.bar cannot be set.

In [243]: test
Out[247]: Foo(bar='bar')

关于python - 如何使数据类中的属性只读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61237131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com