Python Classes

Dataclasses, properties, and dunder methods in minimal form.

  • python class
  • dataclass
  • property
  • dunder
  • classmethod

Python Classes

Dataclasses, properties, and dunder methods in minimal form.

Commands

CommandWhat it does
@dataclass class User: name: strBoilerplate-free data class
@property def total(self):Computed read-only attribute
def __repr__(self):Debug-friendly representation
@classmethod def from_dict(cls, d):Alternative constructor
class APIError(Exception): passCustom exception type

Example

from dataclasses import dataclass
@dataclass
class User:
    name: str
    score: int = 0
print(User("ada", 95))

FAQ

dataclass vs NamedTuple vs pydantic?

dataclass for logic + defaults; NamedTuple for tiny immutable records; pydantic for validated I/O schemas.

When to use @staticmethod?

Namespaced helpers needing neither instance nor class state — rare; module functions often suffice.

SSS

dataclass vs NamedTuple vs pydantic?
dataclass for logic + defaults; NamedTuple for tiny immutable records; pydantic for validated I/O schemas.
When to use @staticmethod?
Namespaced helpers needing neither instance nor class state — rare; module functions often suffice.

Python