Created
November 11, 2019 07:29
-
-
Save a-recknagel/05d2a9e07de10de8132827f621a8d65d to your computer and use it in GitHub Desktop.
ClassVar based dataclass instance counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass, field | |
from typing import ClassVar, List | |
@dataclass | |
class Veget: | |
index: int = field(init=False) | |
name: str | |
price: float | |
quantity: int | |
MAX_COUNT: ClassVar[int] = 3 | |
_veget_index: ClassVar[List["Veget"]] = [] | |
def __post_init__(self): | |
self.index = len(self._veget_index) | |
if self.index >= self.MAX_COUNT: | |
raise RuntimeError("Too many instances") | |
self._veget_index.append(self) | |
print(Veget('tomato', 2.4, 5)) | |
print(Veget('salad', 3.5, 2)) | |
print(Veget('carot', 1.2, 7)) | |
print(Veget('potato', 0.7, 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment