Sub topic 8
Reusing and Overriding Behavior with Inheritance
Inheritance lets one class build on another. The new class gets the attributes and methods of the existing class and can add to them or replace them. This chapter covers how to write a subclass, how Python finds an attribute on an instance, how overriding works, and the mistakes that show up most often.
This chapter assumes you can write a class with __init__, instance methods, and class attributes, as covered in the earlier chapters. It introduces super() only as far as needed. The next chapter covers super() and the method resolution order (MRO) in detail.
The Basic Idea
A base class (also called a parent or superclass) provides behavior. A subclass (also called a child or derived class) inherits from it. You list the base class in parentheses after the subclass name.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def __init__(self, name, tricks=None):
super().__init__(name)
self.tricks = list(tricks or [])
def speak(self):
return "Woof"
for animal in (Animal("Generic"), Dog("Rex")):
print(animal.name, animal.speak())
# Generic ...
# Rex Woof
print(Dog.__mro__) # (<class '__main__.Dog'>, <class '__main__.Animal'>, <class 'object'>)Dog did not define name handling itself. It calls Animal.__init__ through super().__init__(name), which sets self.name. Dog then adds its own attribute, tricks. It also replaces speak() with its own version. The loop treats both objects the same way, because a Dog is an Animal.
Every class in Python 3 inherits from object, even if you don't write it. That is why Dog.__mro__ ends with object.
The "Is-A" Relationship
Inheritance models an is-a relationship. A Dog is an Animal. Python gives you two built-in functions to test this:
class Animal:
pass
class Dog(Animal):
pass
rex = Dog()
print(isinstance(rex, Dog)) # True
print(isinstance(rex, Animal)) # True
print(isinstance(Animal(), Dog)) # False
print(issubclass(Dog, Animal)) # True
print(type(rex) is Animal) # FalseUse isinstance() rather than type(x) is C when you want to accept subclasses. A function that checks type(x) is Animal rejects every Dog, which defeats the purpose of inheritance.
How Attribute Lookup Works
When you write rex.speak, Python does not copy methods into each instance. It searches for the name in a fixed order:
- The instance's own
__dict__. - The instance's class.
- Each base class, in the order given by the MRO.
The first match wins. Overriding a method works because the subclass is searched before its parent.
class Base:
greeting = "hello from Base"
def who(self):
return "Base"
class Child(Base):
def who(self):
return "Child"
c = Child()
print(c.who()) # Child (found on Child first)
print(c.greeting) # hello from Base (not on Child, found on Base)
c.greeting = "hello from the instance"
print(c.greeting) # hello from the instance (instance __dict__ wins)
print(Base.greeting) # hello from Base (class attribute is unchanged)Assigning c.greeting creates a new entry in the instance's __dict__. It does not modify Base.greeting. Reading and writing follow different rules: reads search upward, but writes go to the object you named.
Overriding Methods
A subclass overrides a method by defining one with the same name. Callers don't need to know which version they get. Python picks the one closest to the instance's class.
An override should honor the contract of the method it replaces. Keep the same parameters, or accept more optional ones, and return a compatible kind of value. If Animal.speak() returns a string, Dog.speak() should also return a string. This rule is often called the Liskov substitution principle: code written for the base class should keep working when handed a subclass.
class Report:
def render(self, width=40):
return "Report".center(width)
class SalesReport(Report):
def render(self, width=40): # same signature
return "Sales Report".center(width)
class BrokenReport(Report):
def render(self): # drops the width parameter
return "Broken"
def show(report):
print(report.render(width=20))
show(SalesReport()) # works
try:
show(BrokenReport())
except TypeError as exc:
print("error:", exc)
# error: BrokenReport.render() got an unexpected keyword argument 'width'Python does not check signatures when you override. BrokenReport is accepted silently, and the failure only appears when some caller uses the missing parameter. Tests and type checkers are how you catch this.
Extending Instead of Replacing
Often you want the parent's behavior plus something extra. Call the parent's version with super():
class Logger:
def log(self, message):
return f"LOG: {message}"
class TimestampLogger(Logger):
def log(self, message):
base = super().log(message)
return f"[12:00] {base}"
print(TimestampLogger().log("started")) # [12:00] LOG: startedThis keeps the logic in one place. If Logger.log changes, TimestampLogger picks up the change.
Initializers in Subclasses
If a subclass defines __init__ and does not call the parent's __init__, the parent's setup never runs. Python will not call it for you.
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
class SavingsAccount(Account):
def __init__(self, owner, rate):
# forgot super().__init__(owner)
self.rate = rate
acct = SavingsAccount("Ana", 0.02)
print(acct.rate) # 0.02
try:
print(acct.balance)
except AttributeError as exc:
print("error:", exc)
# error: 'SavingsAccount' object has no attribute 'balance'The fix is one line, super().__init__(owner), placed before you use any attribute the parent sets. If a subclass does not define __init__ at all, it inherits the parent's, and construction works as before.
Class Attributes and Inheritance
Class attributes are inherited like methods. A subclass can shadow one by defining its own, and this is a common way to customize behavior without overriding a method.
class Shape:
sides = 0
def describe(self):
return f"{type(self).__name__} with {self.sides} sides"
class Triangle(Shape):
sides = 3
class Square(Shape):
sides = 4
print(Triangle().describe()) # Triangle with 3 sides
print(Square().describe()) # Square with 4 sides
print(Shape().describe()) # Shape with 0 sidesdescribe() is written once on Shape. Using self.sides means the lookup starts at the instance's real class, so each subclass supplies its own value. Using type(self).__name__ instead of a hard-coded string does the same for the class name.
The shared-mutable-attribute bug from earlier chapters gets worse with inheritance. A mutable class attribute on the base is shared by the base and every subclass that does not replace it.
Inspecting Hierarchies
These tools help when you are unsure where something comes from:
| Tool | What it tells you |
|---|---|
| `isinstance(obj, C)` | Whether `obj` is an instance of `C` or a subclass of `C` |
| `issubclass(A, B)` | Whether `A` is `B` or derives from it |
| `A.__bases__` | The direct parent classes of `A` |
| `A.__mro__` | The full lookup order for `A` |
| `A.__subclasses__()` | The direct subclasses of `A` that currently exist |
| `vars(obj)` | The instance's own attributes (its `__dict__`) |
class A:
pass
class B(A):
pass
class C(B):
pass
print(C.__bases__) # (<class '__main__.B'>,)
print(A.__subclasses__()) # [<class '__main__.B'>]
print(C.__mro__[1:]) # (<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)Built-in Types as Base Classes
You can subclass built-in types such as dict, list, and str. This is handy for small extensions, but there is an edge case to know about.
class Stack(list):
def push(self, item):
self.append(item)
def peek(self):
return self[-1]
s = Stack()
s.push(1)
s.push(2)
print(s.peek()) # 2
print(len(s), s) # 2 [1, 2]
print(type(s[:1])) # <class 'list'>Stack is a real list, so every list operation works. But slicing returns a plain list, not a Stack. Many built-in methods build their results with the built-in type and ignore your subclass. Overriding one method of dict also does not change related methods. For example, a custom __setitem__ is not called by dict.update(). If you need to customize a container deeply, collections.UserDict and collections.UserList are safer, or you can use composition, which a later chapter covers.
Common Mistakes
- Using inheritance for code reuse alone. If
Stackis not really a kind oflistyou want to expose in full, inheriting gives users methods likeinsert()that break the stack idea. - Changing an override's signature. Callers written for the parent break, as in
BrokenReportabove. - Skipping
super().__init__(). The parent's attributes are missing. - Deep hierarchies. Each extra level adds another place where a behavior might be defined. Hierarchies more than two or three levels deep are hard to read and change.
- Hard-coding the parent name. Writing
Animal.__init__(self, name)works, but it breaks when the base class changes or when multiple inheritance is involved. Prefersuper(). - Checking
type(x) is C. It excludes subclasses. Useisinstance.
Edge Cases
A method that is not overridden is inherited unchanged, including its use of self. Inside it, self is the subclass instance, so any call such as self.speak() reaches the subclass override. This is how a base class method can call behavior that only subclasses define.
class Greeter:
def greet(self):
return f"{self.salutation()}, {self.name}"
def salutation(self):
return "Hello"
class FormalGreeter(Greeter):
def __init__(self, name):
self.name = name
def salutation(self):
return "Good day"
print(FormalGreeter("Ms. Lee").greet()) # Good day, Ms. Leegreet() is defined only on Greeter, yet it prints Good day because self.salutation() finds the override first. This pattern is useful, and it is also why changing a base class method can alter subclass behavior in ways the author did not expect.
Names that start with a double underscore, such as __secret, are rewritten by Python to include the class name (_Greeter__secret). This name mangling prevents accidental clashes with subclass attributes. It is not a security feature.
Exercises
Exercise
A class Base has a method hello() returning "base". Child(Base) does not define hello. After running c = Child(); c.hello = lambda: "instance", what does c.hello() return, and what does Child().hello() return for a new instance?
Show answer
c.hello() returns "instance", because the instance's __dict__ is searched before the class. A new Child() has no such entry, so Child().hello() falls through to Base.hello and returns "base".
Exercise
A subclass defines __init__(self, owner, rate) and sets only self.rate. The parent __init__ sets self.owner and self.balance. Why does reading balance fail, and what is the fix?
Show answer
Python does not run the parent initializer automatically when the subclass defines its own __init__. Add super().__init__(owner) at the start of the subclass __init__ so owner and balance get set.
Exercise
Why does Stack(list) with a push method return a plain list when you slice it, and what are two alternatives if you need a fully customized container?
Show answer
Built-in methods such as slicing construct their result with the built-in list type and ignore the subclass. Two alternatives are collections.UserList (or UserDict for dicts), which routes operations through Python-level methods, and composition, where the class holds a list internally and exposes only the methods it wants.