相关疑难解决方法(0)

如何在冻结的数据类自定义 __init__ 方法中设置属性?

我正在尝试构建一个@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吗?

python python-3.x python-3.7 python-dataclasses

11
推荐指数
4
解决办法
7866
查看次数

如何在asdict中获取@property方法?

我有类似的东西:

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}.

实现上述目标的最干净的方法是什么?

python python-attrs

10
推荐指数
1
解决办法
1515
查看次数