iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Inheritance

A subclass extends a parent class — picking up its attributes and methods, and optionally overriding them.

The shape

PYTHON
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return 'some sound'

class Dog(Animal):
    def speak(self):
        return 'woof'

print(Dog('Rex').name)     # Rex
print(Dog('Rex').speak())  # woof

Calling the parent

PYTHON
class Cat(Animal):
    def __init__(self, name, indoor=True):
        super().__init__(name)
        self.indoor = indoor
    def speak(self):
        return super().speak() + ' meow'

Multiple inheritance & MRO

PYTHON
class Swimmer:
    def swim(self): return 'splash'

class Flyer:
    def fly(self): return 'flap'

class Duck(Animal, Swimmer, Flyer):
    pass

print(Duck.__mro__)   # method resolution order

Python walks the MRO left-to-right when looking up an attribute. With multiple inheritance, super() follows that order.

isinstance & issubclass

PYTHON
d = Dog('Rex')
print(isinstance(d, Dog))     # True
print(isinstance(d, Animal))  # True
print(issubclass(Dog, Animal))# True
Tip: Composition often beats inheritance. "A Truck has an Engine" (composition) usually models reality better than "A Truck is an Engine" (inheritance).

Example

Example
class Animal:
    def __init__(self, name): self.name = name
    def speak(self): return 'some sound'

class Dog(Animal):
    def speak(self): return 'woof'

print(Dog('Rex').speak())
Try it Yourself »

Exercise

Call the parent constructor.

().__init__(name)

Test yourself

Q1. super() refers to…
Q2. isinstance(d, Animal) where d is a Dog(Animal) is…
Q3. Style advice: prefer…

Discussion

Loading…