[英]Dataclass nested within another dataclass does not update data correctly
I generate two different instances of a python dataclass
which includes a nested dataclass
.我生成了一个dataclass
的两个不同实例,其中包括一个嵌套dataclass
。 When I update a value in the nested dataclass
in one instance (but not in the other), the same data is placed in the nested dataclass
in both instances.当我在一个实例中更新嵌套dataclass
中的值时(而不是在另一个实例中),相同的数据将放置在两个实例中的嵌套dataclass
中。 This is not what I expected.这不是我所期望的。
from dataclasses import dataclass
@dataclass
class sub1:
q: int = 10
r: str = "qrst"
@dataclass
class A:
a: int = 1
s1: sub1 = sub1()
if __name__ == '__main__':
a = A()
aa = A()
aa.a = 9
aa.s1.r = "92"
print("a:", repr(a))
print("aa:", repr(aa))
''' Produces --
a: A(a=1, s1=sub1(q=10, r='92'))
aa: A(a=9, s1=sub1(q=10, r='92'))
'''
I expected the nested dataclass
to be updated in only the specified instance ( aa
) and for the nested dataclass
in the other instance ( a
) to remain unchanged.我希望嵌套dataclass
仅在指定实例 ( aa
) 中更新,而另一个实例 ( a
) 中的嵌套dataclass
保持不变。
What am I doing wrong, or is dataclass
the wrong tool?我做错了什么,还是dataclass
是错误的工具?
What you are currently doing is providing a default value for the field.您当前所做的是为该字段提供默认值。 As that value is a mutable object, changes to that object will be visible to all instances of your dataclass.由于该值是可变的 object,因此对该 object 的更改将对数据类的所有实例可见。
What you should do instead is provide a default factory that produces sub1
instances for each new A
instance:您应该做的是提供一个默认工厂,为每个新A
实例生成sub1
实例:
from dataclasses import field
@dataclass
class A:
a: int = 1
s1: sub1 = field(default_factory=sub1)
a = A()
aa = A()
aa.a = 9
aa.s1.r = "92"
print("a:", repr(a)) # a: A(a=1, s1=sub1(q=10, r='qrst'))
print("aa:", repr(aa)) # aa: A(a=9, s1=sub1(q=10, r='92'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.