Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 610
M.Amin Avatar asked Jun 13 '21 06:06

M.Amin


People also ask

How do you find the instance variable of a class?

There are two ways to access the instance variable of class:Within the class by using self and object reference. Using getattr() method.

How does Dataclass work in Python?

DataClass in Python DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented. Parameters: init: If true __init__() method will be generated. repr: If true __repr__() method will be generated.

How do you define a class variable in Python?

A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.

Can Dataclass have methods?

A dataclass can very well have regular instance and class methods. Dataclasses were introduced from Python version 3.7. For Python versions below 3.7, it has to be installed as a library.


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.

like image 160
M.Amin Avatar answered Oct 16 '22 22:10

M.Amin