← Learning Hub
Intermediate

Inheritance, Special Methods and Dataclasses

A child class inherits everything from its parent and can change or add to it. super() calls the parent's version of a method.

As programs grow, you'll find classes that share most of their behaviour - a product and a digital product, a payment and a card payment. Inheritance lets the shared part live once in the parent, so a fix there fixes every child. Use it for real "is a kind of" relationships; for loosely related classes, it's often simpler to keep them separate.

Example
You can edit this code.

Special (dunder) methods

Methods with double underscores let your objects work with Python's built-in tools: print(), len(), ==, + and more.

These special methods are how Python's own types work. When you write len(cart), Python calls cart.__len__(); a == b calls __eq__. By adding them to your classes, your objects feel natural to use - like built-in lists or numbers.

Example
You can edit this code.

Dataclasses: less typing

A @dataclass writes __init__, __repr__ and __eq__ for you. Perfect for classes that mainly hold data.

Example
You can edit this code.
Use field(default_factory=list) for list defaults. A plain = [] would share one list between every object.
Key points
  • Child classes inherit and can override; super() calls the parent.
  • Dunder methods connect your objects to len, print, ==, + and more.
  • @dataclass writes __init__, __repr__ and __eq__ for data classes.

📝 Test yourself

1. What does super().__init__(name, price) do?
2. Which method decides what print(obj) shows?
3. Fill in the decorator that writes __init__ for you:
@ class Point: x: int y: int