Python Inheritance
In this page:
What is Inheritance?
Inheritance lets a child class automatically pick up the attributes and methods of a parent class, so common behavior (like a general Animal.eat() method) only needs to be written once and every subclass (Dog, Cat) gets it for free.
Example: What is Inheritance?
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
pass
Dog().eat()
Creating a Subclass
Writing class Dog(Animal): makes Dog a subclass of Animal -- every method and attribute Animal defines becomes available on Dog instances immediately, even before you add anything Dog-specific to its own body.
Example: Creating a Subclass
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
def bark(self):
print("Woof")
d = Dog()
d.eat()
d.bark()
Method Overriding
If a child class defines a method with the same name as one in its parent, calling that method on a child instance runs the child's version instead -- this is how subclasses customize inherited behavior without touching the parent class at all.
Example: Method Overriding
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof")
Dog().speak()
The super() Function
super() gives a child class a handle back to its parent, most often used inside __init__ as super().__init__(...) to run the parent's setup logic before adding the child's own attributes, so you don't have to duplicate the parent's initialization code.
Example: The super() Function
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
d = Dog("Rex", "Labrador")
print(d.name, d.breed)
Multiple Inheritance
A single class can list more than one parent -- class Duck(Swimmer, Flyer): -- inheriting from both, which is powerful for combining independent capabilities but requires understanding method resolution order once those parents define overlapping method names.
Example: Multiple Inheritance
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()
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: