Classes and objects
Your own types, built around a training config — instances and __init__, where attributes live and the order Python searches them in, methods and self, inheritance, super() and the C3 order, properties, dataclasses and __slots__.
From a dict to a class
In the topic Files and exceptions, except LookupError caught a KeyError. That works because exception types are classes, and a KeyError is a special kind of LookupError. Ask Python for the chain:
>>> KeyError.__mro__
(<class 'KeyError'>, <class 'LookupError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)int, str, list and the file objects from open are classes too. Every object is an instance of some class, and the class decides what the object holds and what it can do. This topic opens the Abstraction module: we write classes of our own.
Our running example is a training configuration. Read from JSON, it is a dict, and a dict forgives too much:
>>> import json
>>> cfg = json.loads('{"lr": 0.001, "epochs": 10}')
>>> cfg["epoch"] = 20
>>> cfg
{'lr': 0.001, 'epochs': 10, 'epoch': 20}The typo "epoch" silently created a new key, and training still runs for 10 epochs. Nothing says which keys a config must have, and type(cfg) is just dict. A class gives the record a name and a fixed way of being made:
class Config:
def __init__(self, lr, epochs=10):
self.lr = lr
self.epochs = epochs>>> c = Config(0.001)
>>> c.lr, c.epochs
(0.001, 10)
>>> type(c), isinstance(c, Config)
(<class '__main__.Config'>, True)Python follows three rules here.
- The
classstatement runs its body. Eachdefin it creates a name in a fresh namespace. At the end, Python builds a class object from that namespace and binds the nameConfigto it, the waydefbinds a function. - Calling the class makes an instance.
Config(0.001)creates an empty object of typeConfig, then calls__init__with that object as the first argument and0.001as the next. __init__initializes; it does not create. It gives the new object its attributes,self.lrandself.epochs, and returnsNone. The callConfig(...)returns the object itself.
Where attributes live
Each instance has its own instance dictionary, obj.__dict__. The class has one too, and it holds what the class body defined. A name assigned in the body is a class attribute, shared by all instances:
class Config:
optimizer = "adam" # class attribute
def __init__(self, lr, epochs=10):
self.lr = lr # instance attributes
self.epochs = epochs>>> a, b = Config(0.001), Config(0.1, 5)
>>> a.__dict__
{'lr': 0.001, 'epochs': 10}
>>> a.optimizer, b.optimizer
('adam', 'adam')
>>> a.optimizer = "sgd"
>>> a.__dict__
{'lr': 0.001, 'epochs': 10, 'optimizer': 'sgd'}
>>> a.optimizer, b.optimizer, Config.optimizer
('sgd', 'adam', 'adam')
>>> del a.optimizer
>>> a.optimizer
'adam'Neither instance has optimizer in its own dictionary, yet both find 'adam': the read fell through to the class. The assignment a.optimizer = "sgd" did not touch the class. It created an entry in a.__dict__ that shadows the class attribute, for a only. Deleting the entry uncovers the class attribute again.
Key idea. Reading obj.name looks in the instance's dictionary, then in the class, then in the class's bases in a fixed order (block 5), and returns the first match. If nothing matches, it raises AttributeError. Assigning obj.name = value always writes to the instance's dictionary. Classes hold what instances share, chiefly methods; instances hold their own data. Properties (block 6) are the one exception you will meet here; the topic The data model gives the full rule.
The common mistake: a mutable class attribute. A list in the class body is one object for every instance:
class Run:
tags = [] # one list for all runs
def tag(self, t):
self.tags.append(t)>>> r1, r2 = Run(), Run()
>>> r1.tag("baseline")
>>> r2.tags
['baseline']
>>> r1.tags is r2.tags is Run.tags
Trueself.tags.append(t) reads self.tags, finds the class's list and changes it in place. This is the shared reference from the topic Values, types and names in a new place. The fix: create the list per instance in __init__, self.tags = [].
Methods and self
A method is a function defined in a class body. The function is ordinary. What is special happens when you reach it through an instance:
class Config:
def __init__(self, lr, epochs=10):
self.lr = lr
self.epochs = epochs
def scaled(self, factor):
return Config(self.lr * factor, self.epochs)
@classmethod
def from_dict(cls, d):
return cls(**d)>>> c = Config(0.001)
>>> Config.scaled
<function Config.scaled at 0x1063d7110>
>>> c.scaled
<bound method Config.scaled of <__main__.Config object at 0x1063cc590>>
>>> m = c.scaled
>>> m.__self__ is c, m.__func__ is Config.scaled
(True, True)
>>> c.scaled(10).lr, Config.scaled(c, 10).lr
(0.01, 0.01)Through the class, Config.scaled is the plain function with two parameters. Through the instance, c.scaled is a bound method: a small object that holds the function (__func__) and the instance (__self__). Calling it calls the function with the instance put in front of the other arguments. So c.scaled(10) is Config.scaled(c, 10), and self is only the name of the first parameter. It is a convention, not a keyword, but every reader expects it. The addresses 0x… differ on every run.
The common mistake: forgetting self. The instance arrives anyway:
class Broken:
def describe():
return "config">>> Broken().describe()
Traceback (most recent call last):
...
TypeError: Broken.describe() takes 0 positional arguments but 1 was given"1 was given" when the call passes nothing means the one argument was the instance. Add self.
Two decorators change what a method receives. A @classmethod gets the class as cls instead of the instance; it is the usual way to write an alternative constructor, like Config.from_dict({"lr": 0.1}) above or from_pretrained in Hugging Face libraries. A @staticmethod gets neither and is a plain function kept in the class. The topic Closures and decorators explains the @ syntax.
Python has no private attributes. A leading underscore, self._cache, means "internal, do not touch from outside" by convention only.
Inheritance and super()
A class can extend another. class StepDecay(Schedule) makes Schedule the base class and StepDecay a subclass. The subclass inherits every attribute it does not define, because the lookup continues into the base. Here is a learning-rate schedule:
class Schedule:
def __init__(self, lr):
self.lr = lr
def lr_at(self, epoch):
return self.lr
def describe(self):
return f"{type(self).__name__}: lr at epoch 4 = {self.lr_at(4)}"
class StepDecay(Schedule):
def __init__(self, lr, gamma, step):
super().__init__(lr)
self.gamma, self.step = gamma, step
def lr_at(self, epoch):
return self.lr * self.gamma ** (epoch // self.step)>>> s = StepDecay(0.1, 0.5, 2)
>>> s.describe()
'StepDecay: lr at epoch 4 = 0.025'
>>> s.__dict__
{'lr': 0.1, 'gamma': 0.5, 'step': 2}
>>> isinstance(s, Schedule), type(s) is Schedule
(True, False)describe is not in StepDecay, so the lookup finds it in Schedule. Inside it, self.lr_at(4) is looked up again on self, which is a StepDecay, and finds StepDecay.lr_at first. The subclass overrides the method, and code written in the base calls the override.
super().__init__(lr) runs the base's __init__, so the base sets up its part of the object. The common mistake is to skip it: then Schedule.__init__ never runs, and describe() fails with AttributeError: ... object has no attribute 'lr'. PyTorch is stricter. A network is a subclass of nn.Module, and assigning a layer before super().__init__() raises at once, because the base has not yet built the registry where it records layers.
Inheritance says "a StepDecay is a Schedule": it must work wherever a Schedule is expected. Composition says "a trainer has a schedule": the object stores another object as an attribute and calls it. When the relation is "has a", prefer composition. A PyTorch network does both: it is an nn.Module and has layers as attributes.
The diamond and the C3 order
A class can have several bases. Then "search the bases" needs an order. The interesting case is the diamond, where two bases share a base. Training-loop callbacks give a natural one:
class Callback:
every = 1
def on_epoch_end(self):
return ["Callback"]
class Logger(Callback):
def on_epoch_end(self):
return ["Logger"] + super().on_epoch_end()
class Checkpoint(Callback):
every = 5
def on_epoch_end(self):
return ["Checkpoint"] + super().on_epoch_end()
class LogAndSave(Logger, Checkpoint):
pass>>> [k.__name__ for k in LogAndSave.__mro__]
['LogAndSave', 'Logger', 'Checkpoint', 'Callback', 'object']
>>> LogAndSave().every
5
>>> LogAndSave().on_epoch_end()
['Logger', 'Checkpoint', 'Callback']
>>> Logger().on_epoch_end()
['Logger', 'Callback']The tuple __mro__ is the method resolution order (MRO): the order in which lookup searches the classes. every is found in Checkpoint before Callback, so it is 5.
Python computes the MRO by the C3 linearization. Write for the MRO of class . For a class with bases :
merge repeatedly looks at the first element of each list, its head. It takes the first head that does not appear in the tail (any later position) of any list, appends that class to the result and removes it from the front of every list. For LogAndSave the lists are [Logger, Callback, object], [Checkpoint, Callback, object] and [Logger, Checkpoint]. Logger is taken first. The next head, Callback, still sits behind Checkpoint in the second list, so it waits, and Checkpoint is taken. Then Callback, then object.
C3 guarantees two things: every class comes before its bases, and each class's bases keep the order its class line lists them in. When no order satisfies both, the class is refused. class Bad(Callback, Logger) asks for Callback before its own subclass, and fails with TypeError: Cannot create a consistent method resolution order (MRO) for bases Callback, Logger.
What super() really means. It is not "my base class". It is "the next class after mine in the MRO of the object's type". For a Logger instance, the next after Logger is Callback. For a LogAndSave instance, the same line in Logger calls Checkpoint.on_epoch_end, a class Logger never mentions. That is how every class in the diamond runs exactly once.
Properties
Sometimes an attribute must be checked when it is written or computed when it is read, without changing the code that uses it. A property does that:
class Config:
def __init__(self, lr, epochs=10):
self.lr = lr # goes through the setter below
self.epochs = epochs
@property
def lr(self):
return self._lr
@lr.setter
def lr(self, value):
if value <= 0:
raise ValueError(f"lr must be positive, got {value}")
self._lr = value
@property
def run_name(self):
return f"lr{self.lr}-ep{self.epochs}">>> c = Config(0.001)
>>> c.lr = 0.01
>>> c.run_name
'lr0.01-ep10'
>>> c.__dict__
{'_lr': 0.01, 'epochs': 10}
>>> Config(0)
Traceback (most recent call last):
...
ValueError: lr must be positive, got 0
>>> c.run_name = "best"
Traceback (most recent call last):
...
AttributeError: property 'run_name' of 'Config' object has no setter@property turns the method lr into an object of type property, stored in the class under the name lr. Reading c.lr calls the getter; assigning calls the setter, even in __init__. That is why Config(0) is rejected. The value itself lives in the instance under another name, _lr. A property without a setter, like run_name, is read-only.
The payoff: you can start with a plain attribute and turn it into a property later, when a check becomes necessary, and no caller changes. That is why Python code rarely has get_lr() and set_lr() methods: c.lr stays the interface.
Dataclasses
Most classes that hold data repeat three methods: an __init__ that copies arguments into attributes, a __repr__ that prints them, and an __eq__ that compares them. The decorator @dataclass writes all three from the annotated fields. Here is the Config this course will reuse:
from dataclasses import dataclass, field
@dataclass
class Config:
lr: float
epochs: int = 10
tags: list = field(default_factory=list)>>> c = Config(0.001)
>>> c
Config(lr=0.001, epochs=10, tags=[])
>>> c == Config(0.001), c is Config(0.001)
(True, False)
>>> Config("fast").lr
'fast'
>>> {c: "run 1"}
Traceback (most recent call last):
...
TypeError: cannot use 'Config' as a dict key (unhashable type: 'Config')The lines lr: float are annotations. They name the fields, and @dataclass reads them. The types are not checked: Config("fast") works. The topic Type hints covers what annotations do. A dataclass compares by field values. Objects that are equal must have equal hashes, and a mutable object's fields can change, so a plain dataclass is made unhashable.
Two options fix the common needs.
- Mutable defaults need a factory.
tags: list = []would repeat the shared-list mistake from block 2, so@dataclassrefuses it with aValueError. Withfield(default_factory=list), each instance gets a fresh list. frozen=Trueforbids assignment to fields and makes instances hashable. A frozen config can be a dictionary key: two runs with equal configs get the same key.
from dataclasses import FrozenInstanceError, replace
@dataclass(frozen=True)
class Config:
lr: float
epochs: int = 10>>> c = Config(0.001)
>>> c.lr = 0.1
Traceback (most recent call last):
...
dataclasses.FrozenInstanceError: cannot assign to field 'lr'
>>> results = {c: 0.93}
>>> results[Config(0.001, 10)]
0.93
>>> replace(c, lr=0.01)
Config(lr=0.01, epochs=10)To change a frozen config, make a new one with replace.
Slots, and what comes next
One problem from block 1 is still open: a typo like c.epoch = 20 silently creates a new attribute, because an ordinary instance accepts any name. A class that declares __slots__ gives that up. Its instances have a fixed set of attributes stored at fixed positions inside the object, and no __dict__ at all. A dataclass gets them with slots=True:
@dataclass(slots=True)
class Config:
lr: float
epochs: int = 10>>> c = Config(0.001)
>>> c.epochs = 20
>>> c.epoch = 20
Traceback (most recent call last):
...
AttributeError: 'Config' object has no attribute 'epoch' and no __dict__ for setting new attributes. Did you mean: 'epochs'?
>>> hasattr(c, "__dict__")
FalseThe typo now fails loudly, and the traceback even suggests the right name. The other gain is memory. We created 100,000 objects with three attributes each and measured them with tracemalloc. CPython 3.14.7 on an arm64 Mac gave the bytes per object below. The numbers change between versions and platforms; older versions stored every instance's attributes in a separate dict, and the saving was larger.
Object with fields x, y, z |
Bytes per object |
|---|---|
a plain dict with three keys |
184 |
ordinary class or plain @dataclass |
96 |
__slots__ or @dataclass(slots=True) |
56 |
The cost is flexibility: no new attributes and some care with multiple inheritance. Slots pay off for many small objects, such as tree nodes or parsed records. For a dozen configs they do not matter. For experiment configs, @dataclass(frozen=True, slots=True) is a good default: fixed fields, no accidental changes, usable as a key.
Our plain classes are still strangers to the language. Here is a history of per-epoch losses:
class Losses:
def __init__(self, values):
self.values = values>>> h = Losses([0.9, 0.5, 0.3])
>>> h
<__main__.Losses object at 0x1063b0590>
>>> len(h)
Traceback (most recent call last):
...
TypeError: object of type 'Losses' has no len()
>>> h == Losses([0.9, 0.5, 0.3])
FalseA list prints, has a length, compares by value and supports + and for. It does so not by magic: each piece of syntax calls a method with a double-underscore name on the object's type. The dataclass simply wrote two of them, __repr__ and __eq__, for us. The next topic, The data model, lists those methods, builds a Vector class that supports them, and completes the attribute lookup rule.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.