⚡0 XP🔥0

Inheritance and Polymorphism

Lesson 27 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Reuse and extend classes with inheritance, call parent methods with super(), override methods, use multiple inheritance, and write polymorphic code.

What is inheritance?#

Inheritance lets a new class (the child) take all the attributes and methods of an existing class (the parent), and then add or change things.

          Animal          <- parent / base class
         /      \
       Dog      Cat       <- child / derived classes

A Dog is an Animal. It gets everything an Animal has (name, eat()) plus its own things (bark()).

हिंदी में समझें

Inheritance यानी विरासत - जैसे बच्चे को माता-पिता से कुछ गुण मिलते हैं, वैसे ही child class को parent class की सारी attributes और methods अपने-आप मिल जाती हैं।

फायदा: एक ही code बार-बार नहीं लिखना पड़ता। Animal में eat() एक बार लिखो, और Dog, Cat, Cow - सबको वह मिल जाएगा। हर child class अपनी खास चीज़ें (जैसे bark(), meow()) अलग से जोड़ सकती है।

Basic inheritance#

▶ Try it YourselfPython
Ctrl + Enter to run

super() - extending the parent's init#

When the child needs extra attributes, define its own __init__ and call the parent's with super():

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

If the child defines __init__ but forgets super().__init__(...), the parent's attributes are never created, and you'll get AttributeError: 'Student' object has no attribute 'name'.

Method overriding#

A child can replace a parent method by defining one with the same name:

▶ Try it YourselfPython
Ctrl + Enter to run

Polymorphism#

Polymorphism ("many forms") means the same method call works on different types of objects, each responding in its own way. In the loop above, n.send() did different things for each type - and the loop didn't need any if to check the type.

▶ Try it YourselfPython
Ctrl + Enter to run
Did you know?

Python uses duck typing: "If it walks like a duck and quacks like a duck, it's a duck." The shapes above don't even share a parent class - they just all have an area() method, and that's enough.

हिंदी में समझें

Polymorphism का मतलब है "एक नाम, कई रूप"।

उदाहरण: TV remote का power button - TV पर दबाओ तो TV चालू, AC remote पर दबाओ तो AC चालू। बटन (method का नाम) एक ही है, पर हर मशीन (object) अपने तरीके से काम करती है।

Code में: shape.area() - Square के लिए side², Circle के लिए πr², Triangle के लिए ½ × base × height। Loop को यह जानने की ज़रूरत नहीं कि object किस type का है।

Types of inheritance#

Type Structure Example
Single A → B class Dog(Animal)
Multilevel A → B → C Animal → Mammal → Dog
Hierarchical A → B, A → C Animal → Dog, Animal → Cat
Multiple A + B → C class FlyingCar(Car, Plane)

Multiple inheritance and MRO#

▶ Try it YourselfPython
Ctrl + Enter to run

When two parents have a method with the same name, Python follows the MRO (Method Resolution Order) - left to right as written in the class definition.

isinstance() and issubclass()#

▶ Try it YourselfPython
Ctrl + Enter to run

Abstract base classes (preview)#

To force child classes to implement a method, use abc:

from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class UPI(Payment):
    def pay(self, amount):
        return f"Paid Rs. {amount} via UPI"

# Payment() -> TypeError: Can't instantiate abstract class
print(UPI().pay(500))

Summary#

  • class Child(Parent): inherits all attributes and methods.
  • Use super().__init__(...) to let the parent initialise its part.
  • Overriding = redefining a parent method in the child; call the original with super().method().
  • Polymorphism = same method name, different behaviour per class.
  • Python supports single, multilevel, hierarchical and multiple inheritance (resolved by MRO).

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Vehicle and Car

Create class Vehicle with __init__(self, brand, wheels) and method describe() returning "<brand> with <wheels> wheels".

Create class Car(Vehicle) whose __init__(self, brand) calls the parent with wheels=4.

2

Shapes (polymorphism)

Create classes Square(side) and Circle(radius), each with an area() method. Square area = side², circle area = 3.14 × r². Then complete total_area(shapes) to return the sum of areas of any list of shapes.

3

Override a method

Employee.salary_slip() returns "<name>: <salary>". Create Manager(Employee) that takes an extra bonus and overrides salary_slip() to return "<name>: <salary> + bonus <bonus>".

Quick Quiz

Q1.

In class Dog(Animal):, which is the parent class?

Q2.

What does super().__init__(name) do?

Q3.

What is method overriding?

Q4.

What is isinstance(Dog(), Animal) if Dog inherits from Animal?

Q5.

What is polymorphism?