我正在尝试构建一个@dataclass定义架构但实际上并未使用给定成员实例化的模型。(基本上,我@dataclass为了其他目的劫持了方便的语法)。这几乎就是我想要的:
@dataclass(frozen=True, init=False)
class Tricky:
thing1: int
thing2: str
def __init__(self, thing3):
self.thing3 = thing3
Run Code Online (Sandbox Code Playgroud)
但是我FrozenInstanceError在__init__方法中得到了一个:
dataclasses.FrozenInstanceError: cannot assign to field 'thing3'
Run Code Online (Sandbox Code Playgroud)
我需要frozen=True(为了哈希)。有什么方法可以在__init__冻结上设置自定义属性@dataclass吗?
我有类似的东西:
from attr import attrs, attrib
@attrs
class Foo():
max_count = attrib()
@property
def get_max_plus_one(self):
return self.max_count + 1
Run Code Online (Sandbox Code Playgroud)
现在当我这样做时:
f = Foo(max_count=2)
f.get_max_plus_one =>3
Run Code Online (Sandbox Code Playgroud)
我想将其转换为字典:
{'max_count':2, 'get_max_plus_one': 3}
Run Code Online (Sandbox Code Playgroud)
当我使用时,attr.asdict(f)我没有得到@property. 我只得到
{'max_count':2}.
实现上述目标的最干净的方法是什么?