我想创建数据类现有实例的副本并对其进行修改。
假设我们有一个数据类和该数据类的一个实例:
from dataclasses import dataclass, field, InitVar, replace
@dataclass
class D:
a: float = 10. # Normal attribute with a default value
b: InitVar[float] = 20. # init-only attribute with a default value
c: float = field(init=False) # an attribute that will be defined in __post_init__
def __post_init__(self, b):
self.c = self.a + b
d1 = D()
Run Code Online (Sandbox Code Playgroud)
让我们定义一个实例并尝试制作一个副本(我已经尝试过这篇文章中提出的解决方案):
replace方法:d2 = replace(d1, **{})
Run Code Online (Sandbox Code Playgroud)
抛出错误
InitVar 'b' must be specified with replace()
Run Code Online (Sandbox Code Playgroud)
这似乎是一个已报告的错误,但我不确定是否有任何进展。
__dict__ …