Python OOP
Python Inheritance
Inheritance lets a new class reuse the attributes and methods of an existing class, so you can build specialised classes without repeating code.
Parent and Child Classes
The existing class is called the parent (or base/super) class, and the new class that reuses it is the child (or derived/sub) class. You create inheritance by putting the parent class name in parentheses after the child's name.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def bark(self):
print(f"{self.name} barks")
d = Dog("Rex")
d.speak()
d.bark()Rex makes a sound
Rex barksUsing super()
super() gives you access to the parent class's methods, most commonly to call the parent's __init__ so you do not have to repeat its setup code inside the child class.
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def bark(self):
print(f"{self.name} the {self.breed} barks")
d = Dog("Rex", "Labrador")
d.bark()Single vs Multiple Inheritance
Single inheritance means a class inherits from just one parent, which is the most common case. Multiple inheritance means a class inherits from more than one parent class at the same time.
class Swimmer:
def swim(self):
print("Swimming")
class Flyer:
def fly(self):
print("Flying")
class Duck(Swimmer, Flyer):
pass
d = Duck()
d.swim()
d.fly()When multiple parents define the same method name, Python decides which one to use based on the Method Resolution Order (MRO) — roughly, it searches left to right through the parent list. You can inspect it with ClassName.__mro__.
| Type | Description |
|---|---|
| Single inheritance | child inherits from exactly one parent |
| Multiple inheritance | child inherits from two or more parents |
| super() | calls the parent class's version of a method |
Use inheritance when a child "is a" specialised type of the parent, e.g. Dog is an Animal — this keeps your class hierarchy meaningful.
