Python Inheritance
Inheritance lets a new class take on the attributes and methods of an existing class, so you can reuse code and extend behavior without starting over.
Inheritance models an "is a" relationship between classes. A more specific class, called the child or subclass, builds on a more general class, called the parent or base class. The child automatically gains everything the parent defines and may add new features or change existing ones. This keeps shared logic in one place instead of repeating it across similar classes.
Creating a subclass
You declare inheritance by writing the parent class name in parentheses after the child class name. In the example, Cat inherits the describe method from Animal without redefining it, because a cat is a kind of animal.
A child class inheriting from a parent
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} is an animal."
class Cat(Animal):
def meow(self):
return f"{self.name} says meow."
c = Cat("Milo")
print(c.describe()) # inherited: Milo is an animal.
print(c.meow()) # new: Milo says meow.Overriding methods and using super()
A subclass can replace a parent method by defining one with the same name; this is called overriding. Often you still want the parent's version to run as part of the new one, and super() gives you access to it. This is common in __init__ when the child needs the parent's setup plus its own.
Extending the parent with super()
class Vehicle:
def __init__(self, brand):
self.brand = brand
def info(self):
return f"Vehicle brand: {self.brand}"
class Car(Vehicle):
def __init__(self, brand, doors):
super().__init__(brand) # run the parent's __init__
self.doors = doors
def info(self):
base = super().info() # reuse the parent's method
return f"{base}, doors: {self.doors}"
my_car = Car("Toyota", 4)
print(my_car.info()) # Vehicle brand: Toyota, doors: 4- Inheritance expresses an "is a" relationship and promotes reuse.
- Write the parent name in parentheses to inherit from it.
- Override a method by defining one with the same name in the child.
- Call super() to reuse the parent's implementation.