10 / 22 · Abstraction
Classes and objects
How to define your own types with class: instances and __init__, where attributes live and the order in which Python looks them up, methods and self, inheritance with super and the C3 method resolution order, properties, dataclasses and __slots__.
On this page 12
The previous note caught errors by their type: except ValueError catches a ValueError and every exception type derived from it. Those types are classes, and so are int, str, list and the file objects that open returns. Every object in Python is an instance of some class, and the class decides what the object holds and what can be done with it. This note shows how to write your own classes: how an instance is made, where its attributes are stored, the exact order in which Python searches for an attribute, how methods receive the instance as self, how one class extends another, and the tools that remove the boilerplate: properties, dataclasses and __slots__.
Conventions. As in the rest of the course, everything runs on CPython 3.14.7. Classes are defined in a code block, and a REPL session (>>>) that uses them follows it. Memory addresses such as 0x108f31be0 differ on every run.
Baseline: a dictionary as a record#
Before classes, a bank account can be a dictionary, and the operations on it can be functions that take the dictionary:
def deposit(account, amount):
account["balance"] += amount
return account["balance"]
>>> acct = {"owner": "Ada", "balance": 100}
>>> deposit(acct, 50)
150
>>> acct["balanse"] = 150
>>> acct
{'owner': 'Ada', 'balance': 150, 'balanse': 150}
It works, and the dictionaries note explains why lookups in it are fast. Where it fails is structure. Nothing says which keys an account must have, so the misspelt key "balanse" silently creates a new entry. Nothing ties deposit to accounts: it accepts any dictionary with a "balance" key. And type(acct) is dict, so neither a reader nor a program can ask whether this object is an account. A class gives the record a name, a fixed way of being made, and the operations that belong to it.
A class and its instances#
A class statement creates a class object and binds a name to it, the way def creates a function object and binds its name. Calling the class creates an instance:
class Account:
interest = 0.02
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
>>> a = Account("Ada", 100)
>>> b = Account("Grace")
>>> a.deposit(50)
150
>>> type(a), type(a) is Account
(<class '__main__.Account'>, True)
The rules, in the order Python applies them:
- The class statement runs its body. The body is ordinary code. Each assignment and each
defin it creates a name in a fresh namespace: hereinterest,__init__anddeposit. When the body ends, Python builds the class object from that namespace and bindsAccountto it. - Calling the class makes an instance.
Account("Ada", 100)first creates an empty object whose type isAccount(the job of the method__new__, which classes rarely define), then calls__init__with the new object as the first argument and"Ada"and100as the others. __init__initializes, it does not create. Its job is to give the new object its attributes,self.owner = ownerandself.balance = balance. It must returnNone; the callAccount(...)returns the object itself.
A name that refers to the class, such as Account, works like every other name in the course: MyAccount = Account binds a second name to the same class object, and isinstance(a, MyAccount) is then True.
Where attributes live#
Each instance has its own instance dictionary, obj.__dict__, which maps attribute names to objects. The class has a dictionary too, and it holds what the class body defined:
>>> a.__dict__
{'owner': 'Ada', 'balance': 150}
>>> b.__dict__
{'owner': 'Grace', 'balance': 0}
>>> Account.__dict__["interest"]
0.02
>>> a.interest, b.interest
(0.02, 0.02)
>>> a.interest = 0.05
>>> a.__dict__
{'owner': 'Ada', 'balance': 150, 'interest': 0.05}
>>> a.interest, b.interest, Account.interest
(0.05, 0.02, 0.02)
>>> del a.interest
>>> a.interest
0.02
>>> a.nothing
Traceback (most recent call last):
...
AttributeError: 'Account' object has no attribute 'nothing'
Read the session line by line. Neither instance has interest in its own dictionary, yet both find 0.02: the read fell through to the class. The assignment a.interest = 0.05 did not change the class. It created a new entry in a.__dict__, which from then on shadows the class attribute for a only. Deleting that entry uncovers the class attribute again.
The exception to both rules is a data descriptor defined in the class, such as a property (below): it is consulted before the instance dictionary on a read, and it intercepts the write. The data model note gives the complete rule. Everything else in this note follows from the simple version.
The common mistake: a mutable class attribute. A list defined in the class body is one object, shared by every instance:
class Basket:
items = []
def add(self, x):
self.items.append(x)
>>> p = Basket()
>>> q = Basket()
>>> p.add("apple")
>>> q.items
['apple']
>>> p.items is q.items is Basket.items
True
self.items.append(x) is a read of self.items, not an assignment to it, so it finds the class’s list and changes it in place. This is the shared-reference surprise of the names note in a new place. The fix is to create the list per instance, in __init__: self.items = []. Recognize it by the symptom: one instance’s change shows up in another that never touched it.
Methods and self#
A method is a function defined in a class body. Nothing about the function is special; what is special is what happens when you reach it through an instance:
>>> Account.deposit
<function Account.deposit at 0x108fdc9e0>
>>> a = Account("Ada", 100)
>>> a.deposit
<bound method Account.deposit of <__main__.Account object at 0x108f31be0>>
>>> m = a.deposit
>>> m.__self__ is a, m.__func__ is Account.deposit
(True, True)
>>> m(10)
110
>>> Account.deposit(a, 10)
120
>>> a.deposit is a.deposit
False
Through the class, Account.deposit is the plain function, and it takes two arguments. Through the instance, a.deposit 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 a.deposit(10) and Account.deposit(a, 10) do the same thing, and self is just the name the function gives its first parameter. The name is a convention, not a keyword, but every Python programmer expects it.
A bound method is created on each access, which is why a.deposit is a.deposit is False (the two are still equal under ==). The data model note shows the mechanism that builds them.
The common mistake: forgetting self. A method defined without a parameter still receives the instance:
>>> class Broken:
... def hello():
... return "hi"
...
>>> Broken().hello()
Traceback (most recent call last):
...
TypeError: Broken.hello() takes 0 positional arguments but 1 was given
“Takes 0 but 1 was given”, when the call visibly passes nothing, means the instance was the one argument. Add self.
Two decorators change what a method receives. A @classmethod receives the class instead of the instance, and is the usual way to write an alternative constructor, such as Account.from_dict(d); from_pretrained in Hugging Face’s libraries is one. A @staticmethod receives neither and is a plain function kept in the class’s namespace. The decorators note explains the @ syntax.
Python has no private attributes. A leading underscore, self._balance, is a convention that means “internal, do not use from outside”. Two leading underscores, self.__balance, make Python rename the attribute to _Account__balance inside the class body, which prevents a subclass from clobbering it by accident; it is not a security measure.
Inheritance and super()#
A class can be defined as an extension of another: class Dog(Animal) makes Animal the base class of Dog, and Dog a subclass of Animal. The subclass inherits every attribute it does not define itself, because attribute lookup continues into the base.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
def describe(self):
return f"{type(self).__name__} {self.name}: {self.speak()}"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
return f"{self.name} barks"
>>> d = Dog("Rex", "collie")
>>> d.describe()
'Dog Rex: Rex barks'
>>> d.__dict__
{'name': 'Rex', 'breed': 'collie'}
>>> isinstance(d, Animal), issubclass(Dog, Animal), type(d) is Animal
(True, True, False)
>>> Dog.__mro__
(<class '__main__.Dog'>, <class '__main__.Animal'>, <class 'object'>)
describe is not in Dog, so the lookup finds it in Animal. Inside it, self.speak() is looked up again on self, a Dog, and finds Dog.speak first: the subclass overrides the base’s method, and code written in the base calls the override. super().__init__(name) calls the next __init__ after Dog’s in the MRO, here Animal.__init__, so that the base sets up its part of the object. Every class ultimately derives from object, which supplies defaults such as __repr__ and __eq__.
The common mistake: forgetting super().__init__. If Dog.__init__ did not call it, Animal.__init__ would never run, and d.name would raise AttributeError: 'Dog' object has no attribute 'name'. PyTorch makes this mistake loud: a network is a subclass of nn.Module, and assigning a layer to self before calling super().__init__() raises AttributeError: cannot assign module before Module.__init__() call, because the base class has not yet created the registry in which it records layers (the training pipeline in the Deep Learning course).
Multiple inheritance and the MRO#
A class can have several bases. Then “search the bases” needs an order, and the interesting case is the diamond, where two bases share a base of their own:
class A:
kind = "from A"
def hello(self):
return ["A"]
class B(A):
def hello(self):
return ["B"] + super().hello()
class C(A):
kind = "from C"
def hello(self):
return ["C"] + super().hello()
class D(B, C):
def hello(self):
return ["D"] + super().hello()
>>> [k.__name__ for k in D.__mro__]
['D', 'B', 'C', 'A', 'object']
>>> D().kind
'from C'
>>> D().hello()
['D', 'B', 'C', 'A']
>>> B().hello()
['B', 'A']
Attribute lookup: the instance, then the classes in MRO order
d.kindfirst looks in the instance dictionary, which is empty.- Then in
D, which defines onlyhello. - Then in
B, which also defines onlyhello. - Then in
C, which defineskind = "from C": found, and the search stops. Aalso defineskind, but it comes afterCin the MRO, so its value is never seen.
The rule. The MRO of a class is computed by the C3 linearization (Barrett et al., 1996), adopted by Python in version 2.3 (Simionato). Write for the MRO of class , as a list. For a class with no bases other than object, . For a class with bases :
merge repeatedly takes the head (first element) of the first list whose head does not appear in the tail (any later position) of any list; it appends that class to the result and removes it from the front of every list where it is the head. If no list has such a head, there is no consistent order, and the class statement fails.
Worked example. and . For :
Line by line: , the head of the first list, appears in no tail, so it is taken (second line). The new head of the first list is , but is still in the tail of , so the merge passes over it and takes , the head of the next list (third line). Now and then object head every remaining list and are taken in turn (fourth line). The third line is the step that matters: taking before would put before its own subclass . C3 guarantees two properties: every class comes before all of its bases, and the bases of each class keep the order in which its class statement listed them. The Code section implements the merge in a dozen lines and checks it against D.__mro__.
When no order satisfies both properties, Python refuses to create the class:
class A: ...
class B(A): ...
class X(A, B): ...
Traceback (most recent call last):
...
TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B
X(A, B) asks for A before B, while B(A) requires B before A.
What super() really means. super().hello() inside B does not mean “the base class of B”. It means “the class after B in the MRO of the object’s type”. For a B instance that is A, so B().hello() gives ['B', 'A']. For a D instance, the MRO is D, B, C, A, so the same line in B calls C.hello, a class that B never mentions; that is how D().hello() reaches every class exactly once. This cooperative use of super() is what makes diamonds safe: each class calls super() once, and the MRO strings the calls together. It works only if every class in the chain calls super() and accepts the arguments passed along it.
Composition against inheritance#
Inheritance says “a Dog is an Animal”: a Dog can be passed to every function that expects an Animal and must behave correctly there. Composition says “a Trainer has a model”: the object holds other objects as attributes and calls them.
class Stack(list): # inheritance: a stack is a list?
def push(self, x):
self.append(x)
class Stack2: # composition: a stack has a list
def __init__(self):
self._items = []
def push(self, x):
self._items.append(x)
def pop(self):
return self._items.pop()
Stack inherits all of list, including insert(0, x), sort() and indexing, so nothing stops code from breaking the last-in-first-out discipline. Stack2 exposes exactly the two operations a stack has, and its list can be replaced by a collections.deque without changing any caller. The usual advice (Fluent Python, ch. 14) is to prefer composition and to inherit when the subclass really is a special case of the base, or when a framework asks for it. Deep learning code does both: a network is an nn.Module (inheritance, because the framework calls forward, collects parameters and moves the model between devices), and it has layers, each an nn.Module held as an attribute (composition).
Properties#
Sometimes an attribute should be computed when it is read, or checked when it is written, without changing the code that uses it. A property does that:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter below
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError(f"below absolute zero: {value}")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
>>> t = Temperature(25)
>>> t.celsius, t.fahrenheit
(25, 77.0)
>>> t.celsius = 100
>>> t.fahrenheit
212.0
>>> t.__dict__
{'_celsius': 100}
>>> t.fahrenheit = 0
Traceback (most recent call last):
...
AttributeError: property 'fahrenheit' of 'Temperature' object has no setter
>>> t.celsius = -300
Traceback (most recent call last):
...
ValueError: below absolute zero: -300
@property turns the method celsius into an object of type property, stored in the class under the name celsius. Reading t.celsius calls the getter, and assigning calls the setter, even though the syntax is that of a plain attribute. The value itself lives in the instance under another name, _celsius; storing it as self.celsius inside the getter would call the getter again and recurse until Python stops it. A property without a setter is read-only.
The point of properties is that you can start with a plain attribute and turn it into a property later, when you need a check or a computation, and no caller has to change. That is why Python code has no get_balance() and set_balance() methods: obj.balance stays the interface.
Dataclasses#
Most classes that hold data repeat the same three methods: an __init__ that copies its arguments into attributes, a __repr__ that prints them, and an __eq__ that compares them. The decorator @dataclass (PEP 557, Python 3.7) writes them from the class’s annotated fields:
from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float = 0.0
>>> p = Point(1.5)
>>> p
Point(x=1.5, y=0.0)
>>> p == Point(1.5, 0.0), p is Point(1.5, 0.0)
(True, False)
>>> {Point(1, 2)}
Traceback (most recent call last):
...
TypeError: cannot use 'Point' as a set element (unhashable type: 'Point')
The lines x: float are annotations: they name the fields and their types, and @dataclass reads them to generate the methods. The types are not checked; Point("a") works. The type hints note explains what annotations do and do not do. A dataclass compares by value, and because objects that compare equal must have equal hashes, a mutable dataclass is made unhashable. The data model note explains that rule.
Three options cover most needs:
- Mutable defaults need a factory.
items: list = []would be the shared-list mistake above, so@dataclassrefuses it withValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. Writeitems: list = field(default_factory=list), and each instance gets a new list. frozen=Truemakes assignment to a field raiseFrozenInstanceError: cannot assign to field 'lr', and makes the instances hashable, so they can be dictionary keys and set elements. Frozen dataclasses are a good fit for experiment configurations: two runs with equal configurations have equal keys.slots=True(Python 3.10) gives the class__slots__, the subject of the next section.
@dataclass(frozen=True, slots=True)
class Config:
lr: float
epochs: int = 10
>>> c = Config(0.001)
>>> c
Config(lr=0.001, epochs=10)
>>> c.lr = 0.1
Traceback (most recent call last):
...
dataclasses.FrozenInstanceError: cannot assign to field 'lr'
>>> {c: "run 1"}[Config(0.001)]
'run 1'
__slots__ and the memory of an instance#
An ordinary instance can receive any attribute at any time, because its attributes behave as a dictionary. A class that declares __slots__ gives that up: its instances have a fixed set of attributes, stored in fixed positions inside the object, and no __dict__ at all.
class P:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
>>> p = P(1, 2)
>>> p.z = 3
Traceback (most recent call last):
...
AttributeError: 'P' object has no attribute 'z' and no __dict__ for setting new attributes
The gain is memory. The Code section creates 100,000 instances with three attributes each, all referring to one shared float so that only the instances themselves are counted, and measures the memory they take with tracemalloc. CPython 3.14.7 on an Apple M1 (macOS, arm64):
Object with fields x, y, z | Bytes per object |
|---|---|
| ordinary class | 96 |
ordinary class, after reading obj.__dict__ once | 160 |
class with __slots__ (also @dataclass(slots=True)) | 56 |
a plain dict with three keys | 184 |
The second row explains the first. CPython keeps an ordinary instance’s attribute values in a compact array attached to the object, with the attribute names shared by all instances of the class, and builds an actual dictionary only when code asks for __dict__; reading it once costs 64 more bytes per object. __slots__ drops even the compact array’s bookkeeping: 56 bytes, 40 fewer than the ordinary class. A @dataclass without slots=True measured the same 96 bytes as the ordinary class. sys.getsizeof reports 48 bytes for the ordinary instance, because it counts the object but not the attribute storage attached to it; measure memory with tracemalloc, as the Code section does, rather than with getsizeof. These numbers belong to this version and machine: older versions of CPython stored every instance’s attributes in a separate dictionary, and the saving from __slots__ was larger.
The cost is flexibility: no new attributes, no __dict__, and some care with multiple inheritance. Use __slots__ for classes with many small instances, such as the nodes of a tree or the records of a parser; for a dozen objects it does not matter.
Where the ML courses use classes#
- PyTorch models are subclasses of
nn.Modulethat callsuper().__init__(), hold their layers as attributes and defineforward(Deep Learning). Assigning a layer toselfis how it gets registered; the base class intercepts the assignment, a mechanism the data model note explains. - scikit-learn estimators are classes whose
__init__only stores the hyperparameters as attributes, and whosefitcomputes learned attributes with a trailing underscore, such ascoef_, and returnsself, so thatmodel.fit(X, y).predict(X_new)can be chained. - Configurations of experiments are often frozen dataclasses, printed in logs through the generated
__repr__and compared with the generated__eq__.
What changed#
| Dictionary as a record (the baseline) | Class | |
|---|---|---|
| What the object is | type(acct) is dict | type(a) is Account; isinstance works |
| Where the data lives | keys of the dictionary | the instance dictionary, or fixed slots with __slots__ |
| Operations | separate functions that accept any dictionary | methods, found through the class and bound to the instance |
| A misspelt field | silently creates a new key | creates a new attribute too, unless the class uses __slots__ or a frozen dataclass |
| Shared behaviour | copy the functions | inheritance, searched in MRO order |
| Checks on assignment | none | properties |
| Boilerplate | none, and no structure | @dataclass writes __init__, __repr__ and __eq__ |
Limitations#
- The lookup rule here is the simple version. Properties, methods and other descriptors change it in a precise way, and a class can intercept lookups with
__getattr__and__getattribute__; the data model note has the full rule. - Classes are themselves objects, instances of
type, and the class statement can be customized by a metaclass. Few programs need one, and this course does not cover them. - The memory table is one measurement on one machine with one version of CPython. The layout of instances changed in 3.11 and again later, and will change again.
- Nothing in Python enforces privacy or types: underscores are conventions, and dataclass annotations are not checked at run time.
What you should remember#
classruns its body and builds a class object from the names it defined. Calling the class creates an instance and runs__init__on it.- Reading
obj.namesearches the instance’s dictionary, then the classes of the MRO in order; assigningobj.namewrites to the instance. Mutable class attributes are shared by all instances. obj.methodis a bound method: the function plus the instance, which arrives asself.- The MRO is the C3 linearization: each class before its bases, bases in the order listed.
super()means “next in the MRO of the object’s type”, not “my base class”. - Prefer composition; inherit for a true “is a” relation or when a framework asks for it.
- Properties make computed and checked attributes look like plain ones.
@dataclasswrites the boilerplate methods;frozen=Truemakes instances immutable and hashable;__slots__(orslots=True) saves memory per instance.
Code#
The script exercises each mechanism of the note: the instance dictionary against class attributes, a function that reports where plain lookup finds a name, a bound method taken apart, the diamond with the C3 merge implemented by hand and compared with D.__mro__, a property, a frozen dataclass with slots, and the memory measurement behind the table. It needs only the standard library; run it with python -I classes.py. It takes about a second.
"""Classes: attribute lookup, bound methods, the MRO, properties and memory per instance (Python 3.14)."""
import tracemalloc
from dataclasses import FrozenInstanceError, dataclass, field
# 1. Instance attributes live in the instance; class attributes are shared
class Account:
interest = 0.02 # a class attribute
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
a, b = Account("Ada", 100), Account("Grace")
a.interest = 0.05 # creates an instance attribute; the class is unchanged
print(a.__dict__, b.__dict__, b.interest)
def where(obj, name):
"""Where plain attribute lookup finds `name`: the instance, or the first class in the MRO."""
if name in vars(obj):
return "instance"
for klass in type(obj).__mro__:
if name in vars(klass):
return klass.__name__
return None
print(where(a, "interest"), where(b, "interest"), where(a, "deposit"), where(a, "__repr__"))
# 2. A bound method is the function plus the instance
m = a.deposit
print(m.__self__ is a, m.__func__ is Account.deposit, m(10), Account.deposit(a, 10))
# 3. A diamond, its MRO, and C3 computed by hand
class A:
kind = "from A"
def hello(self):
return ["A"]
class B(A):
def hello(self):
return ["B"] + super().hello()
class C(A):
kind = "from C"
def hello(self):
return ["C"] + super().hello()
class D(B, C):
def hello(self):
return ["D"] + super().hello()
def c3(cls):
"""The C3 linearization: cls, then a merge of the bases' linearizations and the list of bases."""
seqs = [c3(base) for base in cls.__bases__] + [list(cls.__bases__)]
result = [cls]
while any(seqs):
seqs = [s for s in seqs if s]
for s in seqs: # the first head that is in no tail
head = s[0]
if not any(head in t[1:] for t in seqs):
break
else:
raise TypeError("no consistent MRO")
result.append(head)
seqs = [t[1:] if t[0] is head else t for t in seqs]
return result
print([k.__name__ for k in c3(D)], c3(D) == list(D.__mro__))
print(D().hello(), D().kind, where(D(), "kind"))
try:
type("X", (A, B), {}) # A before its own subclass B: impossible
except TypeError as err:
print("TypeError:", err)
# 4. A property: computed on read, validated on write
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError(f"below absolute zero: {value}")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(100)
print(t.fahrenheit, t.__dict__)
try:
t.celsius = -300
except ValueError as err:
print("ValueError:", err)
# 5. Dataclasses: generated __init__, __repr__, __eq__; frozen and slots
@dataclass(frozen=True, slots=True)
class Config:
lr: float
epochs: int = 10
tags: tuple = ()
@dataclass
class Batch:
items: list = field(default_factory=list)
c = Config(0.001)
print(c, c == Config(0.001, 10), {c: "run 1"}[Config(0.001)], hasattr(c, "__dict__"))
try:
c.lr = 0.1
except FrozenInstanceError as err:
print("FrozenInstanceError:", err)
print(Batch().items is Batch().items)
# 6. Memory per instance with three attributes, measured with tracemalloc
class Plain:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
class Slotted:
__slots__ = ("x", "y", "z")
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def plain_with_dict(x, y, z):
p = Plain(x, y, z)
p.__dict__ # reading __dict__ makes CPython build a real dict
return p
N, v = 100_000, 1.5 # one shared value, so only the instances are counted
for name, make in [("Plain", Plain), ("Plain after __dict__", plain_with_dict),
("Slotted", Slotted), ("dict", lambda x, y, z: {"x": x, "y": y, "z": z})]:
objs = [None] * N
tracemalloc.start()
for i in range(N):
objs[i] = make(v, v, v)
used = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
print(f"{name:21s} {used / N:5.0f} bytes per object")
# Output with CPython 3.14.7 on macOS (arm64); the byte counts differ across versions and platforms:
# {'owner': 'Ada', 'balance': 100, 'interest': 0.05} {'owner': 'Grace', 'balance': 0} 0.02
# instance Account Account object
# True True 110 120
# ['D', 'B', 'C', 'A', 'object'] True
# ['D', 'B', 'C', 'A'] from C C
# TypeError: Cannot create a consistent method resolution order (MRO) for bases A, B
# 212.0 {'_celsius': 100}
# ValueError: below absolute zero: -300
# Config(lr=0.001, epochs=10, tags=()) True run 1 False
# FrozenInstanceError: cannot assign to field 'lr'
# False
# Plain 96 bytes per object
# Plain after __dict__ 160 bytes per object
# Slotted 56 bytes per object
# dict 184 bytes per object
where ignores descriptors, so it answers the question of the simple lookup rule: deposit is found in Account and __repr__ in object. type("X", (A, B), {}) is the function form of a class statement, used here so that the failing class can be caught with try.
Next#
The Account and Point-like classes of this note, without @dataclass, print as <__main__.Account object at 0x…>, compare equal only to themselves, and cannot be added, measured with len or looped over. Built-in types can, and not by magic: len(x), x + y, for and with each call a method with a double-underscore name on the object’s type. The next note lists those methods, builds a Vector class that supports them step by step, and completes the attribute lookup rule with descriptors.
References#
- Python documentation (3.14): The Python Tutorial, §9 Classes; Data model, §3.3.2 (customizing attribute access,
__slots__);dataclasses;tracemalloc; Descriptor Guide. - M. Simionato. The Python 2.3 Method Resolution Order. Python documentation, HOWTO.
- K. Barrett, B. Cassels, P. Haahr, D. A. Moon, K. Playford, P. T. Withington. A Monotonic Superclass Linearization for Dylan. OOPSLA, 1996.
- E. V. Smith. PEP 557 — Data Classes. 2017.
- L. Ramalho. Fluent Python, 2nd ed. O’Reilly, 2022. Ch. 5 (data class builders), ch. 11 (a Pythonic object,
__slots__), ch. 14 (inheritance), ch. 22 (properties). - B. Slatkin. Effective Python, 3rd ed. Addison-Wesley. Chapter on classes and interfaces.
- PyTorch documentation.
torch.nn.Module.