我想替换数据类实例的属性,类似于namedtuple._replace()
,即制作原始对象的更改副本:
from dataclasses import dataclass
from collections import namedtuple
U = namedtuple("U", "x")
@dataclass
class V:
x: int
u = U(x=1)
u_ = u._replace(x=-1)
v = V(x=1)
print(u)
print(u_)
print(v)
这将返回:
U(x=1)
U(x=-1)
V(x=1)
如何在数据类对象中模仿此功能?