Skip to content

Classes

How to write a plain Python class for any job: a config object, an API client, a domain record or a model. Special methods are on the dunder methods page, and record classes on data containers.

I want to… Use… Example
define a class class Name: with a CapWords name class ApiClient:
set the starting state of each object def __init__(self, ...): self.base_url = base_url
create an instance call the class client = ApiClient("https://api.example.com")
see what an instance stores vars(obj) (same as obj.__dict__) {'base_url': '...', 'timeout': 5.0}
check the class of an object isinstance(obj, Cls); type(obj) for the exact class isinstance(u, User)
read an attribute by a string name getattr(obj, name, default) getattr(cfg, "debug", False)
share one constant across all instances a class attribute MAX_RETRIES = 3
give each instance its own list or dict create it in __init__ self.headers = {}
accept an optional mutable argument default None, then build it self.tags = list(tags) if tags else []
force arguments to be named * in the signature def __init__(self, url, *, timeout=5.0)
count or register all instances a class attribute changed through the class User.count += 1
build an object from a dict, a file or env vars @classmethod alternative constructor Config.from_env()
a helper that needs no instance or class @staticmethod, or a module function Slug.is_valid("a-b")
a computed attribute without () @property order.total
validate every assignment of an attribute @property plus @name.setter user.age = -1 raises ValueError
a read-only attribute @property with no setter AttributeError on assignment
compute an expensive value once per object @functools.cached_property report.summary
mark a name as internal one leading underscore self._session, _parse()
avoid a name clash in subclasses two leading underscores (name mangling) self.__cache → _Base__cache
avoid a keyword or built-in name one trailing underscore class_, type_, id_
hint “an instance of this class” typing.Self def from_env(cls) -> Self:
hint a class attribute typing.ClassVar count: ClassVar[int] = 0
hint a constant that must not change typing.Final MAX_RETRIES: Final = 3
name the class in its own body Self, or a quoted name "Node" children: list["Node"]
return the object for chaining return self query.where(...).limit(10)
show the object clearly in logs __repr__ User(name='ada', age=36)
a class mostly made of fields @dataclass see data containers
copy an object copy.copy(obj), copy.deepcopy(obj) deep copy for nested lists
list the public methods [n for n in dir(obj) if not n.startswith("_")]
from typing import ClassVar, Self
class User:
"""A user account.""" # docstring: help(User) shows it
MIN_AGE: ClassVar[int] = 13 # class attribute: one value for all users
count: ClassVar[int] = 0 # class-wide counter
def __init__(self, name: str, age: int, *, admin: bool = False) -> None:
self.name = name # instance attributes: one set per object
self.age = age
self.admin = admin
User.count += 1 # change a counter through the class
def greet(self) -> str: # instance method: works on self
return f"Hi, {self.name}"
@classmethod
def from_dict(cls, data: dict[str, object]) -> Self: # alternative constructor
return cls(str(data["name"]), int(str(data["age"]))) # cls: subclass-safe
@staticmethod
def is_valid_name(name: str) -> bool: # static method: no self, no cls
return name.isidentifier()
@property
def is_adult(self) -> bool: # computed on every read, no parentheses
return self.age >= 18
def __repr__(self) -> str: # developer view: print(), logs, the REPL
return f"{type(self).__name__}(name={self.name!r}, age={self.age!r})"
u = User.from_dict({"name": "ada", "age": "36"})
print(u, u.greet(), u.is_adult, User.is_valid_name("ada lovelace"), User.count)
Output
User(name='ada', age=36) Hi, ada True False 1
Piece Syntax Notes
class statement class Name: runs the body once and binds a class object to Name
initializer def __init__(self, ...) fills a new object; must return None
instance attribute self.x = value usually created in __init__
class attribute x = value in the body stored in vars(Cls); shared
instance method def m(self, ...) obj.m(a) is Cls.m(obj, a)
class method @classmethod def m(cls, ...) gets the class; works through subclasses
static method @staticmethod def m(...) gets nothing extra
property @property def x(self) read as obj.x
docstring first string in the body help(Cls), Cls.__doc__
class Reading:
unit = "°C"
def __init__(self, value: float) -> None:
self.value = value
r = Reading(21.5)
print(vars(r), "unit" in vars(r), "unit" in vars(Reading)) # instance vs class
r.unit = "K" # creates an instance attribute that shadows the class value
print(r.unit, Reading.unit, Reading(0.0).unit)
del r.unit # removes the instance value: the class value shows again
print(r.unit, type(r).__name__, getattr(r, "missing", "n/a"))
Output
{'value': 21.5} False True
K °C °C
°C Reading n/a

Reading obj.name searches, in order:

Step Where Found when
1 a data descriptor on the class (@property) the class defines a property with that name
2 the instance namespace, vars(obj) self.name = ... ran
3 the class, then each base in type(obj).__mro__ a method or a class attribute
4 __getattr__, if the class defines it fallback for missing names
5 nothing AttributeError: 'C' object has no attribute 'name'

obj.name = value writes to vars(obj), unless the class has a property (or another data descriptor) with that name; then its setter runs.

Built-in Does Example
vars(obj) the instance namespace (a dict) vars(cfg)
hasattr(obj, "x") True if lookup finds x hasattr(resp, "json")
getattr(obj, "x", default) lookup by a string name getattr(settings, key, None)
setattr(obj, "x", value) assignment by a string name for k, v in d.items(): setattr(cfg, k, v)
delattr(obj, "x") del obj.x by name
type(obj) the exact class type(u) is User
isinstance(obj, Cls) Cls or a subclass; a tuple means “any of” isinstance(x, (int, float))
dir(obj) all names lookup can find, sorted tab completion
obj.__class__, Cls.__name__, Cls.__module__ class, its name, its module type(self).__name__ in a repr
class Cart:
tax_rate = 0.2 # immutable shared default: safe
items_wrong: list[str] = [] # BUG: one list for every cart
created = 0
def __init__(self, owner: str) -> None:
self.owner = owner
self.items: list[str] = [] # right: one list per cart
Cart.created += 1 # right: changes the class counter
self.created += 1 # wrong: reads the class value, writes an instance attribute
a, b = Cart("ada"), Cart("bob")
b.tax_rate = 0.1 # b gets its own value; a still sees the class value
a.items_wrong.append("pen") # mutates the shared list
print(a.tax_rate, b.tax_rate, b.items_wrong, a.items is b.items)
print(Cart.created, b.created)
Output
0.2 0.1 ['pen'] False
2 3
Operation Effect
obj.x (read) the instance value if any, else the class value
obj.x = v creates or replaces an instance attribute; the class value is untouched
Cls.x = v changes the value for every instance without its own x
obj.x.append(v) mutates the object that lookup found; a class list is shared by all
self.n += 1 reads the class value, writes an instance attribute: the class counter does not move
Cls.n += 1 or type(self).n += 1 changes the class counter (type(self) gives each subclass its own counter)

Good class attributes: constants (MAX_RETRIES = 3), defaults that instances may shadow, registries and counters changed through the class, and type hints marked ClassVar.

Instance method Class method Static method
Decorator none @classmethod @staticmethod
First parameter self (the instance) cls (the class) none
Called as obj.m() Cls.m() or obj.m() Cls.m() or obj.m()
Reads instance state yes no no
Sees the subclass through type(self) yes: cls is the subclass no
Typical use behavior of one object alternative constructors, class-wide settings a helper of the class topic
Often better as — — a module-level function

Alternative constructors you already use:

Call Builds
dict.fromkeys(["a", "b"], 0) {'a': 0, 'b': 0}
datetime.fromisoformat("2024-05-01T13:30:00") a datetime
datetime.fromtimestamp(0, tz=UTC) a datetime from Unix time
date.today(), Path.cwd(), Path.home() from the environment
int.from_bytes(b"\x01\x00", "big") 256
bytes.fromhex("ff00"), float.fromhex(...) from text
Decimal.from_float(0.1), Fraction.from_float(0.5) exact numbers
pd.DataFrame.from_records(rows), pd.DataFrame.from_dict(d) a DataFrame
import os
from collections.abc import Iterable, Mapping
from typing import Self
class ApiClient:
def __init__(
self,
base_url: str, # required
*, # everything after * is keyword-only
timeout: float = 5.0, # optional, immutable default
headers: Mapping[str, str] | None = None, # optional mutable: default None
retries: int = 3,
) -> None:
if not base_url.startswith(("http://", "https://")):
raise ValueError(f"base_url must start with http(s)://, got {base_url!r}")
self.base_url = base_url.rstrip("/") # normalize once
self.timeout = timeout
self.headers = dict(headers or {}) # copy: the caller's dict stays separate
self.retries = retries
self._calls = 0 # internal state starts here too, never later
@classmethod
def from_env(cls, environ: Mapping[str, str] = os.environ) -> Self:
return cls(environ["API_URL"], timeout=float(environ.get("API_TIMEOUT", "5")))
@classmethod
def from_pairs(cls, base_url: str, pairs: Iterable[tuple[str, str]]) -> Self:
return cls(base_url, headers=dict(pairs))
def url(self, path: str) -> str:
return f"{self.base_url}/{path.lstrip('/')}"
env = {"API_URL": "https://api.example.com/", "API_TIMEOUT": "2.5"}
c = ApiClient.from_env(env) # inject the mapping: testable without real env vars
print(c.url("/users/7"), c.timeout, c.headers)
print(ApiClient.from_pairs("http://localhost:8000", [("Accept", "json")]).headers)
try:
ApiClient("api.example.com")
except ValueError as err:
print(err)
Output
https://api.example.com/users/7 2.5 {}
{'Accept': 'json'}
base_url must start with http(s)://, got 'api.example.com'
Pattern Code Why
required, then optional def __init__(self, url, timeout=5.0) defaults go last
keyword-only options def __init__(self, url, *, timeout=5.0) calls read clearly; you can reorder options later
mutable default tags=None → self.tags = list(tags or []) tags=[] is shared by every call
copy what you store self.headers = dict(headers) outside changes do not leak in
validate early raise ValueError(...) in __init__ or a setter a bad object never exists
set every attribute in __init__ self._cache = None hasattr checks and typos stay rare
keep __init__ cheap no network, no file reads build in from_file() / connect() instead
many ways to build @classmethod constructors that call cls(...) one __init__ stays the single source of truth
delegate to the parent super().__init__(...) see inheritance
mostly fields @dataclass writes __init__, __repr__ and __eq__ for you

__new__ creates the object and __init__ fills it. Override __new__ only to subclass an immutable type (int, str, tuple) or to control instance creation (caching).

from functools import cached_property
class Product:
def __init__(self, name: str, price: float) -> None:
self.name = name
self.price = price # runs the setter: new objects are validated too
@property
def price(self) -> float: # getter
return self._price # stored under another name
@price.setter
def price(self, value: float) -> None: # setter: the same name
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"price must be a number, got {type(value).__name__}")
if value < 0:
raise ValueError(f"price must be >= 0, got {value}")
self._price = float(value)
@property
def slug(self) -> str: # read-only: no setter
return self.name.lower().replace(" ", "-")
class Report:
def __init__(self, values: list[float]) -> None:
self.values = values
@cached_property
def total(self) -> float: # runs once, then stored in vars(self)
print("computing...")
return round(sum(self.values), 2)
p = Product("USB Cable", 9.99)
for bad in (-1, "9.99"):
try:
p.price = bad
except (ValueError, TypeError) as err:
print(type(err).__name__, err)
print(p.price, p.slug)
try:
p.slug = "x"
except AttributeError as err:
print(err)
rep = Report([79.99, 249.0])
print(rep.total, rep.total, "total" in vars(rep))
Output
ValueError price must be >= 0, got -1
TypeError price must be a number, got str
9.99 usb-cable
property 'slug' of 'Product' object has no setter
computing...
328.99 328.99 True
Pattern Code Use
computed, read-only @property only full_name, total, is_expired
validated attribute @property + @x.setter storing self._x prices, ports, ages, ranges
validate in __init__ too self.x = x (not self._x = x) the setter checks new objects
normalize on write self._email = value.strip().lower() one canonical form
deleter @x.deleter rare: clean up on del obj.x
computed once per object @functools.cached_property parsed config, a summary; del obj.x resets it
the same check on many attributes a descriptor class see dunder methods
a plain stored value a plain attribute add a property later without changing callers

Do not write get_x() / set_x() methods. Start with a plain attribute. Turn it into a property when it needs a check; callers do not change.

Name Meaning Enforced?
name public interface —
_name internal: do not use from outside no, a convention; from m import * skips module-level _names
__name mangled to _ClassName__name inside the class body only the rename; not privacy
__name__ Python’s special names (__init__, __repr__) never mangled; do not invent new ones
name_ avoids a keyword or built-in (class_); a learned attribute in scikit-learn (coef_) no
CapWords class names: HttpClient, UserRepository PEP 8
UPPER_CASE constants: MAX_RETRIES PEP 8; Final makes type checkers enforce it
class Base:
def __init__(self) -> None:
self.__calls = 0 # stored as _Base__calls
def tick(self) -> int:
self.__calls += 1
return self.__calls
class Child(Base):
def __init__(self) -> None:
super().__init__()
self.__calls = "child data" # stored as _Child__calls: no clash
c = Child()
print(c.tick(), sorted(vars(c)), hasattr(c, "__calls"), c._Base__calls)
Output
1 ['_Base__calls', '_Child__calls'] False 1

Mangling rewrites identifiers in the class body (also other.__x), never strings: getattr(obj, "__x") is not rewritten. Use it only to protect internals of a class meant for subclassing. Use _x everywhere else.

Hint Meaning
def save(user: User) -> None a class is a type
-> Self (from typing) “an instance of the class this method runs on”; alternative constructors, chaining, __enter__
-> "Node" a quoted forward reference, before the class name exists
from __future__ import annotations annotations are stored as strings and not evaluated; no quotes needed (3.14 defers evaluation by default)
x: ClassVar[int] = 0 a class attribute, not a per-instance field (matters for dataclasses)
MAX: Final = 3 a constant; type checkers reject reassignment
self.items: list[str] = [] annotate an instance attribute where you create it
type[User] the class itself, not an instance: def make(cls: type[User]) -> User
@typing.override (3.12+) marks a method that must override a parent method
from typing import Self
class Query:
def __init__(self, table: str) -> None:
self.table = table
self.filters: list[str] = []
self.max_rows: int | None = None
def where(self, condition: str) -> Self: # Self: chaining keeps the subclass type
self.filters.append(condition)
return self
def limit(self, n: int) -> Self:
self.max_rows = n
return self
def sql(self) -> str:
where = f" WHERE {' AND '.join(self.filters)}" if self.filters else ""
limit = f" LIMIT {self.max_rows}" if self.max_rows is not None else ""
return f"SELECT * FROM {self.table}{where}{limit}"
print(Query("orders").where("amount > 100").where("region = 'EU'").limit(5).sql())
Output
SELECT * FROM orders WHERE amount > 100 AND region = 'EU' LIMIT 5
Error (last traceback line) Typical cause Fix
TypeError: C.m() takes 0 positional arguments but 1 was given self missing in def m(): def m(self):
NameError: name 'x' is not defined inside a method wrote x instead of self.x self.x
TypeError: C.__init__() missing 1 required positional argument: 'y' an argument missing in C(...) pass it or give a default
TypeError: C.__init__() takes 2 positional arguments but 3 were given an option is keyword-only C(a, timeout=3)
AttributeError: 'C' object has no attribute 'x' typo, never set, or a mangled __x read outside set it in __init__; check vars(obj)
AttributeError: property 'x' of 'C' object has no setter assigning a read-only property, or the setter has another name add @x.setter with the same name
RecursionError: maximum recursion depth exceeded the getter or setter of x uses self.x store the value in self._x
TypeError: __init__() should return None, not 'C' return self in __init__ no return in __init__
AttributeError: 'NoneType' object has no attribute 'limit' a chained method does not return self return self
NameError: name 'C' is not defined at the def line (3.12–3.13) -> C inside the body of class C -> Self or -> "C"
  • Missing self. Symptom: “takes 0 positional arguments but 1 was given”. Fix: the first parameter of an instance method is self.
  • Mutable class attribute. Symptom: one object’s list changes every object. Fix: create lists and dicts in __init__.
  • Mutable default argument. Symptom: def __init__(self, tags=[]) shares one list across calls. Fix: tags=None, then list(tags or []).
  • self.count += 1 on a class counter. Symptom: the class counter stays at 0. Fix: Cls.count += 1 or type(self).count += 1.
  • Hard-coded class name in a class method. Symptom: Sub.from_dict(...) returns a parent object. Fix: return cls(...).
  • Property that recurses. Symptom: RecursionError. Fix: the property x stores and reads self._x.
  • Setter skipped for new objects. Symptom: Product(price=-5) works. Fix: write self.price = price in __init__, not self._price.
  • bool passes a number check. Symptom: isinstance(True, int) is True, so retries=True is accepted. Fix: reject bool first.
  • cached_property goes stale. Symptom: the value does not follow changes in the data. Fix: use @property, or del obj.name after a change. It also does not work with __slots__.
  • __x is not private. Symptom: you expect protection and get a renamed attribute _C__x. Fix: use _x for internal names.
  • Memory address in output. Symptom: print(obj) shows <__main__.C object at 0x...>. Fix: add __repr__.
  • Heavy work in __init__. Symptom: you cannot create an object in a test without a network or a file. Fix: pass the data in, or build it in a @classmethod such as from_file().
  • A class of static methods only. Symptom: no state, every call is Utils.f(...). Fix: use a module of functions.
  • A class with __init__ and one method. Symptom: Thing(x).run() everywhere. Fix: write a function.