Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Created November 11, 2019 07:29
Show Gist options
  • Save a-recknagel/05d2a9e07de10de8132827f621a8d65d to your computer and use it in GitHub Desktop.
Save a-recknagel/05d2a9e07de10de8132827f621a8d65d to your computer and use it in GitHub Desktop.
ClassVar based dataclass instance counter
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