Inheritance in Python: How to Re-use Code in Classes

3D isometric illustration of a parent robot passing traits to a child robot, representing Class Inheritance in Python.

In our Guide to OOP, we created a Dog class. But what if we also need a Cat class? They both have names and ages. Do we have to rewrite all that code? This is where Python inheritance can help simplify and reduce redundancy in your code.

Inheritance lets you create a general “parent” class (like Animal) and then specialized “child” classes (like Dog and Cat) that automatically get all the parent’s features. This illustrates how Python uses inheritance to streamline your programming.

Step 1: The Parent Class

Let’s make a generic Animal class, showcasing a core aspect of inheritance in Python.

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sleep(self):
        print(f"{self.name} is sleeping... Zzz")

Step 2: The Child Class

To inherit from a parent, you put the parent class name in parentheses when defining the child, a fundamental step in using inheritance in Python.

class Dog(Animal):
    # Dog gets __init__ and sleep() for FREE!
    
    def bark(self):
        print("Woof! Woof!")

class Cat(Animal):
    def meow(self):
        print("Meow!")

Step 3: Using Them

fido = Dog("Fido", 3)
whiskers = Cat("Whiskers", 5)

# They can both use the PARENT method
fido.sleep()      # Output: Fido is sleeping... Zzz
whiskers.sleep()  # Output: Whiskers is sleeping... Zzz

# They can use their OWN unique methods
fido.bark()       # Output: Woof! Woof!
# fido.meow()     # ERROR! Dogs can't meow.

Overriding Methods

What if a child needs to do something differently? It can override the parent’s method by defining it again with the same name.

class Cat(Animal):
    def sleep(self):
        print(f"{self.name} is sleeping in a weird sunbeam.")

Now, when a Cat sleeps, it uses its own specialised version of the sleep() method, not the generic Animal one.

Similar Posts

Leave a Reply