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
| Command | What it does |
|---|---|
@dataclass class User: name: str | Boilerplate-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): pass | Custom 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
Python Venv and Environments
Isolate dependencies per project with venv and pinned requirements.
Python Pip Essentials
Install, upgrade, and audit packages with pip like a pro.
Python Basics
Syntax survival kit: variables, loops, f-strings, and errors.
Python Strings
Slice, split, join, and format text efficiently.