Python Classes and OOP #3.1
Each instance can hold its own data and share methods defined on the class. Special methods tell Python how to display and compare instances.
Classes and OOP
What does this code print?
class Bot:
tags = []
a = Bot()
b = Bot()
a.tags.append("rag")
print(b.tags)
# prints: ['rag']
The change went through a, yet b sees it. tags is declared in the class body, so it belongs to the class, and every object made from the class shares it.
- A class is a template.
Bot()creates an instance, an object built from that template. - To read
b.tags, Python looks onbitself first, then on the classBot, then on its parent classes.
The whole lesson is about two things: where attributes and methods live (instance, class, parent class), and which methods Python calls for you. Each row below is one section, with a short example:
| Section | Example | Result |
|---|---|---|
| Declaring a class | bot = Bot("Orbit") | Python creates the object, then calls __init__(bot, "Orbit") |
| Class and instance attributes | self.name = name in __init__, tags = [] in the class body | one name per instance, one tags shared by all |
| Dunder methods | a == b | Python calls a.__eq__(b) |
@property and method kinds | p.label, with no () | runs the label method as if reading an attribute |
| Inheritance and the MRO | class C(A, B): | looks up methods in the order C, A, B, object |
| ABC and Protocol | BrokenLLM(), a class missing complete | TypeError: the object cannot be created |
| dataclass and pydantic | @dataclass on a class with name: str | generates __init__, __repr__, __eq__ |
How some other languages compare
| Job | JS / TS | Java | Go |
|---|---|---|---|
| constructor | constructor | constructor named after the class | a NewBot function (convention) |
| current object | this (implicit) | this (implicit) | receiver (b *Bot) |
| developer string | toString() | toString() | String() |
| equality | none, === compares identity | equals, hashCode | == compares struct fields |
| getter, setter | get x(), set x() | getX, setX methods | none |
| static method | static | static | package-level function |
| inheritance | extends, one parent | extends, one parent | none, use embedding |
| contract | TS interface | interface, needs implements | interface, matched implicitly |
| data record | none | record | struct |
| private member | #name | private | lower-case name |
Declaring a class
The first lines of the Bot class below, taken apart
| Part | Meaning |
|---|---|
class Bot: | declares a class named Bot, written in PascalCase by convention; the body is indented |
def __init__ | the initialiser, which Python calls after creating the object. There is no new keyword |
self | the object being created or called. Python passes it in when you call bot.greet() |
name, model="gpt-4o" | ordinary parameters, optionally with defaults |
self.name = name | creates the attribute name on this object. No field declaration needed first |
class Bot:
def __init__(self, name, model="gpt-4o"):
self.name = name
self.model = model
def greet(self):
return f"Hello, I am {self.name}"
bot = Bot("Orbit")
print(bot.greet())
# prints: Hello, I am Orbit
print(bot.model)
# prints: gpt-4o
print(type(bot))
# prints: <class '__main__.Bot'>
Bot("Orbit"): call the class like a function to create an instance.bot.greet()is reallyBot.greet(bot): the object before the dot is passed in asself.__main__: the module name of the file being run directly.
Class attributes and instance attributes
| Write | Meaning |
|---|---|
max_tokens = 1000 in the class body | class attribute: one copy, shared by every instance |
self.tags = [] in __init__ | instance attribute: each object has its own |
a.max_tokens | read: look on the instance first, then on the class |
a.max_tokens = 2000 | assign: always creates an attribute on the instance; the class is unchanged |
class Bot:
max_tokens = 1000
a = Bot()
b = Bot()
a.max_tokens = 2000
print(a.max_tokens)
# prints: 2000
print(b.max_tokens)
# prints: 1000
print(Bot.max_tokens)
# prints: 1000
Assigning a.max_tokens gives a its own attribute. b still reads the class value.
Trap: a mutable class attribute
Reading is fine, but mutating a class-level list in place changes it for every instance:
class Bot:
tags = []
def __init__(self, name):
self.name = name
def add_tag(self, tag):
self.tags.append(tag)
a = Bot("Orbit")
b = Bot("Orbit-v2")
a.add_tag("rag")
print(b.tags)
# prints: ['rag']
print(a.tags is Bot.tags)
# prints: True
self.tags.append(...) is not an assignment, so it creates no instance attribute. It changes the single list on the class. Same root as the shared mutable default trap in part 2.
The fix: create the list in __init__.
class Bot:
def __init__(self, name):
self.name = name
self.tags = []
def add_tag(self, tag):
self.tags.append(tag)
a = Bot("Orbit")
b = Bot("Orbit-v2")
a.add_tag("rag")
print(a.tags)
# prints: ['rag']
print(b.tags)
# prints: []
Dunder: repr, eq, hash
| Write | Python calls it for | Default if you do not write it |
|---|---|---|
__repr__(self) | repr(x), and print(x) when there is no __str__ | class name and memory address |
__eq__(self, other) | a == b | identity, like a is b |
__hash__(self) | hash(x), dict keys, set members | hash by identity |
With no dunder methods, two objects with the same name are still different:
class Bot:
def __init__(self, name):
self.name = name
a = Bot("Orbit")
b = Bot("Orbit")
print(a) # 0x... is a memory address that changes on every run
# prints: <__main__.Bot object at 0x...>
print(a == b)
# prints: False
print(hash(a) == hash(b))
# prints: False
Add __repr__ and __eq__:
class Bot:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Bot(name={self.name!r})"
def __eq__(self, other):
if not isinstance(other, Bot):
return NotImplemented
return self.name == other.name
a = Bot("Orbit")
b = Bot("Orbit")
print(a)
# prints: Bot(name='Orbit')
print(a == b)
# prints: True
print(Bot.__hash__)
# prints: None
print({a})
# error: TypeError: unhashable type: 'Bot'
isinstance(other, Bot): isotheraBot(or a subclass)?return NotImplemented: says "I do not know how to compare with this type". Python tries the other side and ends withFalseinstead of an error.{a}: a one-item set, which needshash(a), so it fails.
To compare by value and still use the object as a key, write __hash__ from exactly the fields __eq__ uses:
class Bot:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Bot(name={self.name!r})"
def __eq__(self, other):
if not isinstance(other, Bot):
return NotImplemented
return self.name == other.name
def __hash__(self):
return hash(self.name)
a = Bot("Orbit")
b = Bot("Orbit")
print({a, b})
# prints: {Bot(name='Orbit')}
print(len({a, b}))
# prints: 1
The two objects are equal, so the set keeps one. Do this only if name never changes after creation; change it while the object sits in a set and the set looks in the wrong place.
property, classmethod, staticmethod
| Write | Meaning |
|---|---|
@decorator on the line above def | decorator: wraps the function below it to change how it works |
@property | a method read like an attribute: p.label, no () |
@amount.setter | runs on p.amount = ..., used to check the value |
@classmethod | receives the class (named cls by convention) instead of the instance; often an alternative constructor |
@staticmethod | receives neither self nor cls; a plain function kept inside the class |
class Price:
def __init__(self, amount):
self.amount = amount
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
if value < 0:
raise ValueError("amount must be >= 0")
self._amount = value
@property
def label(self):
return f"{self.amount:,} VND"
p = Price(150_000)
print(p.amount)
# prints: 150000
print(p.label)
# prints: 150,000 VND
p.amount = 200_000
print(p.label)
# prints: 200,000 VND
p.amount = -1
# error: ValueError: amount must be >= 0
self.amount = amountin__init__also goes through the setter, soPrice(-1)fails too.raise ValueError(...): raises an error, likethrowelsewhere.- Start with a plain attribute. When you need a check, turn it into a property later; code that reads
p.amountdoes not change.
class Bot:
def __init__(self, name, model):
self.name = name
self.model = model
@classmethod
def from_dict(cls, data):
return cls(data["name"], data["model"])
@staticmethod
def is_valid_name(name):
return name.isalnum()
bot = Bot.from_dict({"name": "Orbit", "model": "gpt-4o"})
print(bot.name, bot.model)
# prints: Orbit gpt-4o
print(Bot.is_valid_name("Orbit"))
# prints: True
print(Bot.is_valid_name("Orbit v2"))
# prints: False
cls(...)creates an object of the class passed in. Called on a subclass,from_dictreturns an object of the subclass.isalnum(): the string has only letters and digits."Orbit v2"has a space, so it isFalse.
Inheritance, super and the MRO
| Write | Meaning |
|---|---|
class SupportBot(Bot): | SupportBot inherits from Bot; the parent goes in brackets |
class C(A, B): | multiple inheritance: several parents, and their order matters |
super().__init__(name) | calls the method of the next class in the MRO, usually the parent |
C.__mro__ | a tuple of classes in the order Python searches for a method |
class Bot:
def __init__(self, name):
self.name = name
def greet(self):
return f"I am {self.name}"
class SupportBot(Bot):
def __init__(self, name, team):
super().__init__(name)
self.team = team
def greet(self):
return super().greet() + f", team {self.team}"
s = SupportBot("Orbit", "billing")
print(s.greet())
# prints: I am Orbit, team billing
print(isinstance(s, Bot))
# prints: True
A subclass with its own __init__ must call super().__init__(...) itself. Python does not call the parent's initialiser for you.
Diamond inheritance
A and B both inherit from Base; C inherits from both A and B:
class Base:
def hello(self):
return "Base"
class A(Base):
def hello(self):
return "A > " + super().hello()
class B(Base):
def hello(self):
return "B > " + super().hello()
class C(A, B):
def hello(self):
return "C > " + super().hello()
print(C().hello())
# prints: C > A > B > Base
print([k.__name__ for k in C.__mro__])
# prints: ['C', 'A', 'B', 'Base', 'object']
super()insideAgoes toB, not toBase.super()means "the next class in the MRO of the running object", not "the parent of this class".Baseruns once, even though two paths lead to it.- The MRO comes from the C3 algorithm: a subclass comes before its parents, and parents keep the order written in the brackets.
k.__name__: the class name as a string.
ABC and Protocol
Both declare the contract "a class must have a complete method". They differ in how a class counts as a match.
| ABC | Protocol | |
|---|---|---|
| Matches by | name (nominal): must inherit | shape (structural): having the methods is enough |
| Checked | at run time: creating an object with a missing method fails | before running, by mypy or the IDE |
| Module | abc | typing |
| Good for | your own classes, when you want an explicit declaration | classes from another library that you cannot make inherit |
The example: code that calls an LLM only needs "something with complete(prompt)", so you can swap the provider (OpenAI, Claude, a fake in tests) without touching ask.
ABC
from abc import ABC, abstractmethod
class LLMProvider(ABC):
@abstractmethod
def complete(self, prompt): ...
class FakeLLM(LLMProvider):
def complete(self, prompt):
return f"echo: {prompt}"
class BrokenLLM(LLMProvider):
pass
def ask(llm, question):
return llm.complete(question)
print(ask(FakeLLM(), "Who is Orbit?"))
# prints: echo: Who is Orbit?
print(isinstance(FakeLLM(), LLMProvider))
# prints: True
BrokenLLM()
# error: TypeError: Can't instantiate abstract class BrokenLLM with abstract method complete
@abstractmethod: a subclass must define this method....(an ellipsis): an empty body, likepass.pass: a statement that does nothing, for where the syntax needs a block.
Protocol
from typing import Protocol
class LLMProvider(Protocol):
def complete(self, prompt: str) -> str: ...
class FakeLLM:
def complete(self, prompt: str) -> str:
return f"echo: {prompt}"
class UpperLLM:
def complete(self, prompt: str) -> str:
return prompt.upper()
def ask(llm: LLMProvider, question: str) -> str:
return llm.complete(question)
print(ask(FakeLLM(), "Who is Orbit?"))
# prints: echo: Who is Orbit?
print(ask(UpperLLM(), "Who is Orbit?"))
# prints: WHO IS ORBIT?
print(FakeLLM.__mro__)
# prints: (<class '__main__.FakeLLM'>, <class 'object'>)
prompt: str,-> str: type hints for the parameter and the return value. Only for readers and mypy.FakeLLM.__mro__showsFakeLLMdoes not inherit fromLLMProvider. It matches only because it hascomplete.- Pass
askan object withoutcomplete: mypy reports it before running; Python only raisesAttributeErrorwhen the call is reached.
dataclass and pydantic
@dataclass | pydantic BaseModel | |
|---|---|---|
| Source | standard library, dataclasses | third-party, pip install pydantic |
| Generates | __init__, __repr__, __eq__ | the same, plus JSON in and out |
| Run-time type check | no: a wrong type is accepted | yes: converts when it can, raises otherwise |
| Use for | internal data you already trust | data from outside: API requests, LLM output, config |
from dataclasses import dataclass, field
@dataclass
class Message:
role: str
content: str
tokens: int = 0
tags: list[str] = field(default_factory=list)
m = Message("user", "Hello Orbit")
print(m)
# prints: Message(role='user', content='Hello Orbit', tokens=0, tags=[])
print(m == Message("user", "Hello Orbit"))
# prints: True
bad = Message("user", "hi", tokens="many")
print(repr(bad.tokens))
# prints: 'many'
role: strin the class body: declares a typed field.@dataclassreads these lines to generate__init__.list[str]: the type hint for a list of strings.field(default_factory=list): a new list for each object. Writingtags: list[str] = []makes the dataclass raiseValueError, exactly because of the mutable class attribute trap.tokens="many"is accepted even though the field saysint.
pydantic is a third-party library; it does not come with Python. The example below ran with pydantic 2.13:
from pydantic import BaseModel
class Message(BaseModel):
role: str
content: str
tokens: int = 0
m = Message(role="user", content="Hello Orbit", tokens="12")
print(repr(m.tokens))
# prints: 12
print(m.model_dump())
# prints: {'role': 'user', 'content': 'Hello Orbit', 'tokens': 12}
Message(role="user", content="hi", tokens="many")
# error: ValidationError: 1 validation error for Message
"12"is converted to the number12(no quotes in itsrepr).- The error message goes on for a few lines, naming the field
tokensand the reason:Input should be a valid integer. model_dump(): turns the object into a dict, ready for JSON.BaseModeltakes arguments by name (role=...), not by position like a dataclass.
Short notes: slots and private names
__slots__ declares the attribute names up front. The object no longer has a __dict__ (the dict that holds attributes), so it uses less memory and rejects unknown attributes:
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.x, p.y)
# prints: 1 2
p.z = 3
# error: AttributeError: 'Point' object has no attribute 'z'
Only worth it when you create millions of small objects. @dataclass(slots=True) (3.10) does it for a dataclass.
Private names: _name is only the "internal" convention and stays accessible. __name (two leading _, none at the end) is renamed by Python to _ClassName__name (name mangling) so a subclass does not overwrite it by accident; it is not security.
Key takeaways
selfis the first parameter, written out.__init__initialises; there is nonew.- Class attributes are shared. A list or dict that belongs to one object is created in
__init__. - Write
__eq__and__hash__becomesNone; to use the object as a key, write__hash__from the same fields. @propertykeeps thep.amountsyntax and still checks the value.@classmethodgives alternative constructors.super()follows the MRO, not the direct parent. See the order withClass.__mro__.- An ABC matches by inheritance, checked at run time. A Protocol matches by shape, checked by mypy.
- A dataclass does not check data; pydantic checks and converts at run time.
Sources
- Classes (Python Tutorial) (opens in a new tab): classes, instances, class attributes, inheritance, name mangling.
- Data model: special method names (opens in a new tab):
__repr__,__eq__,__hash__,__slots__. - The Python 2.3 Method Resolution Order (opens in a new tab): the C3 algorithm.
- abc (opens in a new tab), typing.Protocol (PEP 544) (opens in a new tab), dataclasses (opens in a new tab), pydantic: Models (opens in a new tab).
- Every example with a
# printsline was run on Python 3.11.9; the pydantic example with pydantic 2.13.4.
