How to add the class instance to a class variable in dataclass notation?

Viewed 383

I want to add all of the class instances to a class variable

I want to do this:

class Circle:
    all_circles = []
    def __init__(self, rad):
        self.rad = rad
        self.__class__.all_circles.append(self)

So when ever I make a new circle instance it is added to the all_circle class variable.

How to do this in dataclass notation?

I wanted to replicate the code at the top in @dataclass but I couldn't find anywhere how to do this because I can't access the self.

Something like:

from dataclasses import dataclass
from typing import ClassVar


@dataclass
class Circle:
    rad: int = 1
    all_circles = ClassVar[list] = [] # after this I don't know how to get the self because it is not available
    

But I couldn't find how to do it.

1 Answers

Found the answer

I found a solution after looking at other examples of the dataclass! You can use the __post_init__ function to achieve the same result!

from dataclasses import dataclass
from typing import ClassVar

@dataclass
class Circle:
    rad: int = 1
    all_circles = ClassVar[list["Circle"]] = []

    def __post_init__(self: "Circle") -> None:
        Circle.all_circles.append(self)

If there is a better way to do this please tell me.

Related