Python · Lesson 5

Classes

How Python classes work (explicit self, instance versus class attributes), properties, classmethods and staticmethods, the dunder methods that make objects compare, hash, print and behave like containers, inheritance with super(), composition and duck typing.

12 min read

In short

  • __init__ and explicit self; class body attributes are shared
  • Never put a list or dict in the class body for per-instance state
  • @property for validation, @classmethod for alternate constructors
  • __repr__, __eq__ with __hash__, container dunders
  • super() to extend; composition and duck typing to reuse

Python classes look familiar from C# and TypeScript, and then surprise you in small ways. There's no new, no this, no access modifiers, and no field declarations: an object's attributes are whatever __init__ assigns. self is an ordinary parameter you write out on every regular method. And most of the power comes from dunder methods ("double underscore", like __eq__ and __len__), which plug your class into Python's operators and built-in functions.

Every python snippet has a ▶ Try button. Predict the output, then run it.

A class, __init__ and self

▶ Try
class Account:
    def __init__(self, owner: str, balance: int = 0) -> None:
        self.owner = owner
        self.balance = balance

    def deposit(self, amount: int) -> int:
        self.balance += amount
        return self.balance


acc = Account("ann")             # no `new`: call the class
acc.deposit(50)
print(acc.owner, acc.balance)
print(type(acc).__name__, isinstance(acc, Account))
print(vars(acc))                 # the instance's attributes live in a dict
  • Calling the class creates the object and then calls __init__ on it. __init__ is an initializer, not a constructor: the object already exists when it runs, and it returns None.
  • self is the instance, passed explicitly as the first parameter. acc.deposit(50) is shorthand for Account.deposit(acc, 50). The name self is a convention, but a universal one.
  • Attributes are created by assigning to them (self.owner = owner). There's no field list. Assigning a new attribute anywhere, even from outside, just works, which is flexible and also how typos become bugs.

Because self is explicit, a method you take off an object stays bound to it. There's no lost-this problem as in JavaScript:

▶ Try
class Counter:
    def __init__(self) -> None:
        self.count = 0

    def increment(self) -> None:
        self.count += 1


c = Counter()
inc = c.increment        # a bound method: it remembers c
inc()
inc()
print(c.count)

Instance attributes vs class attributes

Attributes assigned on self belong to one instance. Attributes assigned in the class body belong to the class, and every instance can read them. Lookup goes instance first, then class:

▶ Try
class Order:
    currency = "EUR"                 # class attribute: shared
    tax_rate = 0.2

    def __init__(self, total: int) -> None:
        self.total = total           # instance attribute


a, b = Order(100), Order(200)
print(a.currency, b.currency)
Order.currency = "USD"               # change it on the class: everyone sees it
print(a.currency, b.currency)
a.currency = "GBP"                   # assigning on an instance creates an instance attribute
print(a.currency, b.currency, Order.currency)

Assigning through self never changes the class attribute; it shadows it for that one instance. That makes immutable class attributes (numbers, strings, tuples) safe defaults and constants.

A mutable class attribute is a trap. Mutating it through any instance changes the one shared object:

▶ Try
class Cart:
    items = []                       # one list, shared by every cart

    def add(self, sku: str) -> None:
        self.items.append(sku)       # mutates the class's list, doesn't assign


first, second = Cart(), Cart()
first.add("pen")
print(second.items)                  # second's cart has a pen in it


class FixedCart:
    def __init__(self) -> None:
        self.items: list[str] = []   # one list per instance

    def add(self, sku: str) -> None:
        self.items.append(sku)


first, second = FixedCart(), FixedCart()
first.add("pen")
print(second.items)

It's the same bug as the mutable default argument: one object created once and shared. In TypeScript, a field initializer like items = [] runs per instance; a Python class body runs once. Put per-instance state in __init__.

Properties

Python has no getters and setters by convention. Start with a plain public attribute. If you later need validation or a computed value, turn it into a property and no caller has to change:

▶ Try
class Product:
    def __init__(self, name: str, price_cents: int) -> None:
        self.name = name
        self.price_cents = price_cents      # goes through the setter below

    @property
    def price_cents(self) -> int:
        return self._price_cents

    @price_cents.setter
    def price_cents(self, value: int) -> None:
        if value < 0:
            raise ValueError("price can't be negative")
        self._price_cents = value

    @property
    def price(self) -> str:                 # computed and read-only: no setter
        return f"{self.price_cents / 100:.2f}"


p = Product("pen", 250)
p.price_cents = 199
print(p.price_cents, p.price)
for attempt in [lambda: setattr(p, "price_cents", -1), lambda: setattr(p, "price", "1.00")]:
    try:
        attempt()
    except (ValueError, AttributeError) as e:
        print(type(e).__name__, e)

The value is stored in self._price_cents, with a leading underscore. That's Python's "private": a convention that says "internal, don't touch", not something the language enforces. Because __init__ assigns self.price_cents = ..., even the initial value is validated.

C#TypeScriptPython
Private memberprivate (enforced by the compiler)private (compile time) or #x (runtime)_x by convention
Computed memberpublic int X { get; set; }get x() / set x(v)@property / @x.setter
Read-only{ get; } / readonlyreadonlya property with no setter

A name with two leading underscores (self.__secret) is name-mangled to _ClassName__secret, so a subclass can't clash with it by accident. It isn't access control either, and most codebases stick to one underscore.

@classmethod and @staticmethod

A classmethod receives the class (cls) instead of an instance. Its main job is alternate constructors: Python has no constructor overloading, so you write from_json, from_row, from_string classmethods that parse the input and call cls(...). A staticmethod receives neither; it's a plain function that lives in the class's namespace.

▶ Try
class Temperature:
    def __init__(self, celsius: float) -> None:
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, fahrenheit: float) -> "Temperature":
        return cls((fahrenheit - 32) * 5 / 9)

    @staticmethod
    def is_valid(celsius: float) -> bool:
        return celsius >= -273.15


class Reading(Temperature):
    pass


t = Temperature.from_fahrenheit(212)
print(t.celsius, Temperature.is_valid(-300))
r = Reading.from_fahrenheit(32)
print(type(r).__name__, r.celsius)      # cls is Reading here, so subclasses get the right type

Calling cls(...) rather than Temperature(...) is what makes the alternate constructor work for subclasses too. Reach for @staticmethod sparingly: a module-level function is usually just as good.

Dunder methods: printing

__repr__ is the developer's view: shown in the REPL, in logs, inside lists and in debuggers. It should be unambiguous, ideally valid code that recreates the object. __str__ is the user's view, used by print() and str() and f-strings. If you write only one, write __repr__: str() falls back to it.

▶ Try
class Money:
    def __init__(self, cents: int, currency: str) -> None:
        self.cents = cents
        self.currency = currency

    def __repr__(self) -> str:
        return f"Money({self.cents!r}, {self.currency!r})"

    def __str__(self) -> str:
        return f"{self.cents / 100:.2f} {self.currency}"


m = Money(1999, "EUR")
print(m)                       # __str__
print(repr(m))                 # __repr__
print([m])                     # containers show their items' __repr__
print(f"total: {m}, debug: {m!r}")

Without __repr__ you get <__main__.Money object at 0x10f2...>, which is useless in a log.

Equality and hashing

By default, == on your objects compares identity, like is. Define __eq__ to compare values. Return NotImplemented (not False) for types you don't know, so Python can try the other operand's __eq__:

▶ Try
class Point:
    def __init__(self, x: int, y: int) -> None:
        self.x, self.y = x, y

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)


print(Point(1, 2) == Point(1, 2), Point(1, 2) == "a point")
try:
    {Point(1, 2)}
except TypeError as e:
    print("TypeError:", e)

Defining __eq__ silently sets __hash__ to None, which makes instances unhashable: they can't go in a set or be dict keys. That's deliberate. The rule is "equal objects must have equal hashes", and the default hash (based on identity) would break it. If the object is immutable in practice, define __hash__ from the same fields as __eq__:

▶ Try
class Point:
    def __init__(self, x: int, y: int) -> None:
        self.x, self.y = x, y

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

    def __hash__(self) -> int:
        return hash((self.x, self.y))


visited = {Point(0, 0), Point(1, 2), Point(1, 2)}
print(len(visited), Point(1, 2) in visited)

Don't hash fields that can change. If an object's hash changes while it's in a set, the set can't find it any more. C# has the same contract for Equals and GetHashCode; JavaScript has no hook for ===, and Map/Set always use identity for objects.

Ordering and functools.total_ordering

< calls __lt__, <= calls __le__, and so on. sorted, min and max only need __lt__. If you want all four comparisons, define __eq__ and __lt__ and let functools.total_ordering fill in the rest:

▶ Try
from functools import total_ordering


@total_ordering
class Version:
    def __init__(self, text: str) -> None:
        self.parts = tuple(int(p) for p in text.split("."))

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts == other.parts

    def __lt__(self, other: "Version") -> bool:
        if not isinstance(other, Version):
            return NotImplemented
        return self.parts < other.parts

    def __repr__(self) -> str:
        return f"Version({'.'.join(map(str, self.parts))!r})"


releases = [Version("2.10.0"), Version("2.9.4"), Version("10.0")]
print(sorted(releases))
print(Version("1.2") >= Version("1.1"), max(releases))

Making a class behave like a container

A handful of dunders plug your class into len(), for, in, indexing and truthiness:

You writePython calls
len(x)x.__len__()
for item in x, list(x)x.__iter__()
item in xx.__contains__(item) (falls back to iterating)
x[key], x[1:3]x.__getitem__(key) (a slice arrives as a slice object)
if x:, bool(x)x.__bool__(), else x.__len__() != 0, else always true
x + yx.__add__(y)
▶ Try
class Playlist:
    def __init__(self, name: str, songs: list[str] | None = None) -> None:
        self.name = name
        self._songs = list(songs or [])

    def __len__(self) -> int:
        return len(self._songs)

    def __iter__(self):
        return iter(self._songs)

    def __contains__(self, song: str) -> bool:
        return song.lower() in (s.lower() for s in self._songs)

    def __getitem__(self, index: int | slice):
        return self._songs[index]

    def __repr__(self) -> str:
        return f"Playlist({self.name!r}, {self._songs!r})"


p = Playlist("focus", ["Intro", "Deep Work", "Outro"])
print(len(p), list(p), "deep work" in p)
print(p[0], p[-1], p[:2])
print(bool(p), bool(Playlist("empty")))      # no __bool__: falls back to __len__
for song in p:
    print("-", song)

__iter__ returns an iterator. Delegating to iter(self._songs) is the easy way; the Iterators and Generators topic shows how to write one with yield. Notice that the class wraps a list rather than inheriting from it, which keeps its public surface small. That's composition, below.

Inheritance and super()

A subclass lists its base in parentheses. It inherits every method, can override any of them, and calls the parent's version with super():

▶ Try
class Notifier:
    def __init__(self, sender: str) -> None:
        self.sender = sender

    def format(self, message: str) -> str:
        return f"[{self.sender}] {message}"

    def send(self, to: str, message: str) -> str:
        return f"to {to}: {self.format(message)}"


class SmsNotifier(Notifier):
    def __init__(self, sender: str, max_length: int = 20) -> None:
        super().__init__(sender)             # let the parent set up its part
        self.max_length = max_length

    def format(self, message: str) -> str:   # override, reusing the parent's version
        text = super().format(message)
        return text if len(text) <= self.max_length else text[: self.max_length - 1] + "…"


sms = SmsNotifier("shop")
print(sms.send("+44 7700", "Your order has shipped"))
print(isinstance(sms, Notifier), issubclass(SmsNotifier, Notifier))
  • Forgetting super().__init__(...) in an overriding __init__ is a common bug: the parent's attributes never get set, and you get an AttributeError later, far from the cause.
  • Notifier.send calls self.format(...), and self is the SmsNotifier, so the override runs. Every method is "virtual" in C# terms; there's no virtual/override keyword.
  • Python supports multiple inheritance. super() follows the method resolution order (MRO, see ClassName.__mro__), which is how mixins cooperate. Use it for small mixins, not deep hierarchies.

Exceptions are the place you'll subclass most: class PaymentDeclined(PaymentError): ... lets callers catch a whole family with one except.

Composition over inheritance

Inheritance says "is a": an SmsNotifier is a Notifier and can be used anywhere one is expected. When you only want to reuse code, hold an object and delegate to it instead. A class that inherits from list gets insert, sort, clear and forty other methods that bypass your rules; a class that has a list exposes only what you choose.

▶ Try
class AuditLog:
    def __init__(self) -> None:
        self._entries: list[str] = []     # has a list; is not a list

    def record(self, event: str) -> None:
        if not event:
            raise ValueError("empty event")
        self._entries.append(event)

    def __len__(self) -> int:
        return len(self._entries)

    def __iter__(self):
        return iter(self._entries)


class OrderService:
    def __init__(self, log: AuditLog) -> None:
        self.log = log                    # composed: pass in any log, a fake one in tests

    def place(self, order_id: str) -> None:
        self.log.record(f"placed {order_id}")


log = AuditLog()
OrderService(log).place("A-1")
print(len(log), list(log), hasattr(log, "clear"))

Duck typing

Python checks what an object can do, not what it is: "if it walks like a duck and quacks like a duck". A function that calls .send(...) works with any object that has a send method, with no shared base class or interface:

▶ Try
class EmailNotifier:
    def send(self, to: str, message: str) -> str:
        return f"email {to}: {message}"


class SlackNotifier:
    def send(self, to: str, message: str) -> str:
        return f"slack #{to}: {message}"


def broadcast(notifiers, to: str, message: str) -> list[str]:
    return [n.send(to, message) for n in notifiers]


print(broadcast([EmailNotifier(), SlackNotifier()], "ops", "deploy done"))

This is how len() works on anything with __len__, and for on anything with __iter__. It's like TypeScript's structural typing, but checked at runtime when the method is called. For static checking you can describe the shape with typing.Protocol; the Dataclasses and Typing topic covers that and @dataclass, which writes __init__, __repr__ and __eq__ for you.

__slots__, briefly

Every instance normally carries a __dict__ for its attributes. Declaring __slots__ replaces it with fixed storage for the listed names: instances use less memory, and assigning any other attribute raises AttributeError, which catches typos.

▶ Try
class Pixel:
    __slots__ = ("x", "y")

    def __init__(self, x: int, y: int) -> None:
        self.x, self.y = x, y


p = Pixel(1, 2)
p.x = 5
try:
    p.colour = "red"
except AttributeError as e:
    print("AttributeError:", e)

Use it for classes with millions of instances, or with @dataclass(slots=True). Most classes don't need it.

What interviewers ask

QuestionShort answer
Why is items = [] in a class body a bug?It's one class attribute shared by every instance. Create per-instance state in __init__.
__init__ vs a constructor?__init__ initializes an object that already exists (__new__ creates it).
@classmethod vs @staticmethod?A classmethod gets cls and is used for alternate constructors; a staticmethod gets nothing.
__repr__ vs __str__?Developer view vs user view. str() falls back to __repr__, so write __repr__ first.
Why can't I put my object in a set after defining __eq__?Defining __eq__ sets __hash__ to None. Define __hash__ from the same immutable fields.
How is private done?By convention: _name. __name is name-mangled, not hidden.
What does super() do with multiple inheritance?It calls the next class in the MRO, not necessarily the direct parent.
Inheritance or composition?Inherit for a true "is a" you'll use polymorphically; otherwise hold an object and delegate.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app