小编Rom*_*Zh.的帖子

具有复杂结构的数据类实例的完整副本

我想创建数据类现有实例的副本并对其进行修改。

假设我们有一个数据类和该数据类的一个实例:

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)

让我们定义一个实例并尝试制作一个副本(我已经尝试过这篇文章中提出的解决方案):

  1. 使用replace方法:
d2 = replace(d1, **{})
Run Code Online (Sandbox Code Playgroud)

抛出错误

InitVar 'b' must be specified with replace()
Run Code Online (Sandbox Code Playgroud)

这似乎是一个已报告的错误,但我不确定是否有任何进展。

  1. __dict__ …

python python-3.x python-dataclasses

9
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×1

python-3.x ×1

python-dataclasses ×1