Skip to content
Fullstack Launchpad

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.

By Published Updated 13 min readPython for Engineers Switching Languages

Classes and OOP

What does this code print?

python
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 on b itself first, then on the class Bot, 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:

SectionExampleResult
Declaring a classbot = Bot("Orbit")Python creates the object, then calls __init__(bot, "Orbit")
Class and instance attributesself.name = name in __init__, tags = [] in the class bodyone name per instance, one tags shared by all
Dunder methodsa == bPython calls a.__eq__(b)
@property and method kindsp.label, with no ()runs the label method as if reading an attribute
Inheritance and the MROclass C(A, B):looks up methods in the order C, A, B, object
ABC and ProtocolBrokenLLM(), a class missing completeTypeError: the object cannot be created
dataclass and pydantic@dataclass on a class with name: strgenerates __init__, __repr__, __eq__

How some other languages compare

JobJS / TSJavaGo
constructorconstructorconstructor named after the classa NewBot function (convention)
current objectthis (implicit)this (implicit)receiver (b *Bot)
developer stringtoString()toString()String()
equalitynone, === compares identityequals, hashCode== compares struct fields
getter, setterget x(), set x()getX, setX methodsnone
static methodstaticstaticpackage-level function
inheritanceextends, one parentextends, one parentnone, use embedding
contractTS interfaceinterface, needs implementsinterface, matched implicitly
data recordnonerecordstruct
private member#nameprivatelower-case name

Declaring a class

The first lines of the Bot class below, taken apart

PartMeaning
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
selfthe 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 = namecreates the attribute name on this object. No field declaration needed first
python
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 really Bot.greet(bot): the object before the dot is passed in as self.
  • __main__: the module name of the file being run directly.

Class attributes and instance attributes

WriteMeaning
max_tokens = 1000 in the class bodyclass attribute: one copy, shared by every instance
self.tags = [] in __init__instance attribute: each object has its own
a.max_tokensread: look on the instance first, then on the class
a.max_tokens = 2000assign: always creates an attribute on the instance; the class is unchanged
python
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:

python
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__.

python
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

WritePython calls it forDefault 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 == bidentity, like a is b
__hash__(self)hash(x), dict keys, set membershash by identity

With no dunder methods, two objects with the same name are still different:

python
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__:

python
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): is other a Bot (or a subclass)?
  • return NotImplemented: says "I do not know how to compare with this type". Python tries the other side and ends with False instead of an error.
  • {a}: a one-item set, which needs hash(a), so it fails.

To compare by value and still use the object as a key, write __hash__ from exactly the fields __eq__ uses:

python
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

WriteMeaning
@decorator on the line above defdecorator: wraps the function below it to change how it works
@propertya method read like an attribute: p.label, no ()
@amount.setterruns on p.amount = ..., used to check the value
@classmethodreceives the class (named cls by convention) instead of the instance; often an alternative constructor
@staticmethodreceives neither self nor cls; a plain function kept inside the class
python
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 = amount in __init__ also goes through the setter, so Price(-1) fails too.
  • raise ValueError(...): raises an error, like throw elsewhere.
  • Start with a plain attribute. When you need a check, turn it into a property later; code that reads p.amount does not change.
python
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_dict returns an object of the subclass.
  • isalnum(): the string has only letters and digits. "Orbit v2" has a space, so it is False.

Inheritance, super and the MRO

WriteMeaning
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
python
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:

python
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() inside A goes to B, not to Base. super() means "the next class in the MRO of the running object", not "the parent of this class".
  • Base runs 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.

ABCProtocol
Matches byname (nominal): must inheritshape (structural): having the methods is enough
Checkedat run time: creating an object with a missing method failsbefore running, by mypy or the IDE
Moduleabctyping
Good foryour own classes, when you want an explicit declarationclasses 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

python
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, like pass.
  • pass: a statement that does nothing, for where the syntax needs a block.

Protocol

python
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__ shows FakeLLM does not inherit from LLMProvider. It matches only because it has complete.
  • Pass ask an object without complete: mypy reports it before running; Python only raises AttributeError when the call is reached.

dataclass and pydantic

@dataclasspydantic BaseModel
Sourcestandard library, dataclassesthird-party, pip install pydantic
Generates__init__, __repr__, __eq__the same, plus JSON in and out
Run-time type checkno: a wrong type is acceptedyes: converts when it can, raises otherwise
Use forinternal data you already trustdata from outside: API requests, LLM output, config
python
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: str in the class body: declares a typed field. @dataclass reads 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. Writing tags: list[str] = [] makes the dataclass raise ValueError, exactly because of the mutable class attribute trap.
  • tokens="many" is accepted even though the field says int.

pydantic is a third-party library; it does not come with Python. The example below ran with pydantic 2.13:

python
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 number 12 (no quotes in its repr).
  • The error message goes on for a few lines, naming the field tokens and the reason: Input should be a valid integer.
  • model_dump(): turns the object into a dict, ready for JSON.
  • BaseModel takes 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:

python
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

  • self is the first parameter, written out. __init__ initialises; there is no new.
  • Class attributes are shared. A list or dict that belongs to one object is created in __init__.
  • Write __eq__ and __hash__ becomes None; to use the object as a key, write __hash__ from the same fields.
  • @property keeps the p.amount syntax and still checks the value. @classmethod gives alternative constructors.
  • super() follows the MRO, not the direct parent. See the order with Class.__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