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.
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.
There are two ways to access the instance variable of class:Within the class by using self and object reference. Using getattr() method.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With