codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Python inheritance and polymorphism

Python inheritance and polymorphism

Children reuse and override parents.

Write the parent in brackets: class Cat(Animal). The child inherits everything and can override methods. Polymorphism means the same call (speak()) behaves differently for different classes.

Example code

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

    def speak(self):
        return f"{self.name} makes a sound"

class Cat(Animal):
    def speak(self):
        return f"{self.name} meows"

for a in [Animal("Generic"), Cat("Tom")]:
    print(a.speak())

Run this code in the online editor

← Python classes and objectsPython encapsulation and magic methods →