Inheritance, composition & dunder methods
Use __repr__, __eq__ and friends and choose composition over deep hierarchies.
By Invicly Tech, , in Python Programming from Zero. About 10 minutes to read.
In short
Inheritance lets a subclass reuse and override a parent class's behaviour. Composition builds objects out of other objects instead. Dunder methods like __repr__ and __eq__ make your objects print and compare nicely.
Explained simply
Inheritance means one class builds on another. If you write class Square(Rectangle):, Square gets everything Rectangle has for free, and you only write what is different. The original is called the parent (or base class) and the new one the child (or subclass).
The child can override a method, which means it defines a method with the same name to replace the parent's version. It can also extend a method: run the parent's version with super() and then add its own steps. That is how you reuse code without copying it.
Composition is the other way to reuse code. Instead of saying a Car is an Engine, you say a Car has an Engine and keep one as an attribute. The car asks the engine to start. You can swap in an electric engine without touching the Car class. Most experienced developers reach for composition first.
Dunder methods (short for double underscore, like __repr__) are hooks Python calls for you. Define __repr__ and your object prints nicely. Define __eq__ and == compares contents. Define __len__ and len() works. They make your classes behave like built-in types.
Press Play on a diagram to walk through it one step at a time.
- Circle
- overrides area()
- Rectangle
- overrides area()
- Square(Rectangle)
- calls super().__init__
- Square is a Rectangle
- Reuses parent methods
- Tightly coupled to parent
- Keep hierarchies shallow
- Car has an Engine
- Delegates to parts
- Swap parts easily
- Usually the safer default
- Printing
- __repr__: REPL, lists, debug
- __str__: print(), str()
- Comparing
- __eq__: ==
- __lt__: < and sorted()
- __hash__: sets, dict keys
- Containers
- __len__: len()
- __iter__: for loops
- __contains__: in
- __getitem__: obj[i]
- Truth and maths
- __bool__: if obj
- __add__: +
In depth
Method resolution order: where Python looks
When you call sq.area(), Python searches a fixed list of classes called the MRO (method resolution order). For class Square(Rectangle), the MRO is Square, Rectangle, object. Python uses the first class in that list that defines area. Every class ends with object, which supplies defaults like __repr__ and __eq__.
You can print the MRO with Square.__mro__ or Square.mro(). With multiple inheritance (class C(A, B)), Python builds the order with an algorithm called C3, which keeps each class before its parents and keeps the order you listed bases in. super() follows this same list, so it means "the next class in the MRO", not always "my direct parent".
- 1Square
Defines __init__ only; keep looking
- 2Rectangle
Defines area(): use this one
- 3object
Base of everything; default __repr__, __eq__
Overriding and extending with super()
Overriding replaces the parent's method completely. Extending keeps it and adds to it. To extend, call super().method(...) inside your version. This is most important in __init__: if the child defines its own __init__ and forgets super().__init__(...), the parent's setup never runs and its attributes do not exist. You will see AttributeError later, far from the real cause.
A good override keeps the same parameters and return type as the parent, so code written for the parent still works with the child. This idea is called the Liskov substitution principle: anywhere a Rectangle is expected, a Square should work without surprises.
- Override: def area(self): return math.pi * self.r * self.r
- Extend: super().save(); self.log("saved")
- isinstance(sq, Rectangle) is True for a subclass instance
__repr__, __str__ and __eq__ done right
__repr__ should return a string for developers, ideally one that looks like code to recreate the object, such as Point(x=1, y=2). __str__ is the friendly version for users. print() and str() use __str__, but if you only define __repr__, Python uses it for both. Lists always show the repr of their items, which is why __repr__ matters most.
In __eq__, return NotImplemented (not False) when the other object is a type you do not understand. Python then tries the other side's __eq__, and falls back to an identity check. One more rule: defining __eq__ sets __hash__ to None, so your objects can no longer go in a set or be dict keys. If they are immutable, define __hash__ using the same fields as __eq__.
- f"{obj!r}" forces the repr inside an f-string
- Equal objects must have equal hashes
- functools.total_ordering fills in <=, >, >= from __eq__ and __lt__
Other useful dunder methods
Dunder methods let your objects work with Python's built-in syntax. __len__ makes len(obj) work. __iter__ makes for loops work. __contains__ powers the in operator. __getitem__ enables obj[key]. __bool__ decides whether the object counts as true in an if; without it, Python uses __len__, and if neither exists the object is always true. __add__ defines +, and __lt__ defines <, which also makes sorted() work.
You rarely call dunders yourself. Write len(cart), not cart.__len__(). Implement only the ones that make your class more natural to use; a Playlist with __len__ and __iter__ feels like a built-in collection.
Refactoring a deep hierarchy into composition
Deep trees grow fast. You start with Employee, add Manager(Employee), then RemoteManager(Manager), then RemoteContractorManager. Each new combination needs a new class, and a change near the top can break everything below it.
The fix is to pull each varying behaviour out into its own small object and pass it in. An Employee has a pay_policy (Salaried or Hourly) and a location (Office or Remote). Now any combination is just a different pair of parts, chosen at runtime, and each part is easy to test alone. Use inheritance when the child truly is a kind of the parent and the tree stays one or two levels deep.
- Payroll to Employee: monthly_pay()1monthly_pay()
- Employee to HourlyPolicy: pay(hours=160)2pay(hours=160)
- HourlyPolicy to Employee: 160 x rate3160 x rate
- Employee to Payroll: amount4amount
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Subclass and override methods~50m
- 2Call parent methods with super()~50m
- 3Implement __repr__ and __eq__~50m
- 4Prefer composition for has-a relationships~50m
- 5Refactor a deep hierarchy to composition~50m
Key points
- class Dog(Animal): makes Dog inherit Animal's attributes and methods.
- super().__init__(...) runs the parent's setup before adding your own.
- __repr__ controls how an object prints in the REPL and in debug output.
- __eq__ defines ==; without it, objects compare by identity.
- Prefer composition when the relationship is "has a" rather than "is a".
Key terms
Tap a card to flip it. 0/5 known
Examples
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
def __repr__(self):
return f"{type(self).__name__}({self.w}x{self.h})"
def __eq__(self, other):
return isinstance(other, Rectangle) and (self.w, self.h) == (other.w, other.h)
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
print(Square(3), Square(3).area(), Square(2) == Rectangle(2, 2)) # Square(3x3) 9 TrueExtending a parent with super()
A Notifier sends messages. An EmailNotifier needs the same setup plus an address. Step 1: the child calls super().__init__(name) so the parent sets self.name and self.sent. Step 2: send() is extended: it adds the email part to the text, then calls the parent's send to record it. Without the super().__init__ call, self.sent would not exist and send() would crash.
class Notifier:
def __init__(self, name):
self.name = name
self.sent = []
def send(self, text):
self.sent.append(text)
class EmailNotifier(Notifier):
def __init__(self, name, address):
super().__init__(name)
self.address = address
def send(self, text):
super().send(f"to {self.address}: {text}")
n = EmailNotifier("ops", "ops@example.com")
n.send("disk full"); print(n.sent)A Money value object with equality and hashing
Money should compare by value: 5 EUR equals 5 EUR even if they are different objects. Step 1: __eq__ compares amount and currency, returning NotImplemented for other types. Step 2: because we defined __eq__, we must add __hash__ (using the same fields) to keep Money usable in sets. Step 3: __repr__ shows the values. The set below ends up with two items, not three.
class Money:
def __init__(self, amount, currency):
self.amount, self.currency = amount, currency
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __hash__(self):
return hash((self.amount, self.currency))
def __repr__(self):
return f"Money({self.amount!r}, {self.currency!r})"
print({Money(5, "EUR"), Money(5, "EUR"), Money(5, "USD")})Quick reference
- class Child(Parent): inherits every attribute and method of Parent
- super().__init__(...) runs the parent's setup; forget it and parent attributes are missing
- ClassName.__mro__ shows the exact order Python searches for methods
- print() uses __str__ and falls back to __repr__; lists always show __repr__
- Return NotImplemented from __eq__ for unknown types, not False
- Defining __eq__ removes the default __hash__; add one back for immutable objects
- Ask is-a or has-a: is-a may be inheritance, has-a is composition
Common mistakes
- Deep inheritance chains where behaviour is hard to trace.
- Forgetting to call super().__init__(), leaving parent attributes unset.
- Defining __eq__ without __hash__, which makes instances unhashable.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a Shape class with area() returning 0 and a __repr__ that shows the class name and area. Subclass it as Circle(r) and override area().
- Exercise 2medium
Write a Playlist class that holds song titles and supports len(p), for song in p, and "x" in p, without inheriting from list.
- Exercise 3hard
You have Report, PdfReport(Report), EmailedPdfReport(PdfReport) and EmailedCsvReport(CsvReport). Refactor to one Report class that takes a formatter and a sender object.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Python support multiple inheritance?
- Yes. class C(A, B): inherits from both, and the method resolution order decides which method wins. Keep it for small mixin classes; it gets confusing fast.
- What is the difference between __str__ and __repr__?
- __repr__ is for developers and should be unambiguous; __str__ is for end users. If you write only one, write __repr__.
- Should I inherit from list or dict to make my own collection?
- Usually not. Built-in methods may bypass your overrides. Wrap a list in an attribute (composition), or use collections.UserList or collections.abc base classes.
- What is an abstract base class?
- A class from the abc module that marks methods with @abstractmethod. You cannot create an instance of it until a subclass implements those methods, which documents the required interface.