Mar-14-2024, 03:58 PM
(This post was last modified: Mar-14-2024, 03:58 PM by deanhystad.)
No, it should be ["a"] for the first instance you create and ["b"] for the second instance. The first instance gets deleted when you reassign "c" to the second instance. Does this make things more clear?
@dataclass class C(): mylist: list a: str def __post_init__(self): return self.mylist.append(self.a) x = C("a") print(x.mylist, x.a) y = C("b") print(y.mylist, y.a)If C wasn't a dataclass, and mylist was a class variable it would do what you say,
class C(): mylist = [] def __init__(self, a): self.a = a self.mylist.append(a) c = C("a") print(c.mylist) c = C("b") print(c.mylist)Or if you wanted to use dataclass and still have a class variable.
from dataclasses import dataclass @dataclass class C(): a: str mylist = [] def __post_init__(self): return self.mylist.append(self.a) c = C("a") print(c.mylist) c = C("b") print(c.mylist)