Sub topic 1
Python Inheritance and Method Overriding
Prerequisites
Assume you can define classes, create instances, write methods with self, and call functions with arguments. This chapter uses f-strings and basic print() statements.
Subclasses and What They Inherit
Inheritance lets one class reuse another class's attributes and methods. The existing class is the parent class, or base class. The new class is the subclass, or child class.
Put the parent class in parentheses after the subclass name:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
pass
dog = Dog("Rex")
print(dog.name) # Rex
print(dog.speak()) # Rex makes a soundDog inherits __init__() and speak() from Animal. The pass statement means that Dog adds no new behavior yet.
How Python Finds an Attribute or Method
When Python evaluates dog.speak(), it searches for speak on the dog instance first. It then searches the class, followed by its parent classes. This process is attribute lookup.
An instance attribute can hide a class attribute with the same name. A method defined directly on a subclass also takes priority over an inherited method.
Overriding a Method in a Subclass
Overriding means defining a subclass method with the same name as a parent method. Python then calls the subclass version for subclass instances.
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
print(Animal("Generic").speak()) # Generic makes a sound
print(Dog("Rex").speak()) # Rex barksThe parent method still exists. The override changes which implementation Python selects for Dog objects.
Extending the Parent Method with `super()`
Use super() to access the next implementation in the inheritance chain. This is useful when the subclass should add behavior rather than replace the parent behavior.
class LoudDog(Dog):
def speak(self):
return super().speak().upper() + "!"
print(LoudDog("Rex").speak()) # REX BARKS!Here, super().speak() calls Dog.speak(). The subclass then transforms its result. Calling super() avoids duplicating the parent's code and keeps the relationship explicit.
Exercise
Which method runs for Dog("Rex").speak() if Dog defines speak() but Animal also defines speak()?
Show answer
Dog.speak() runs because a method defined on the subclass is found before the inherited parent method.