1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Inheritance

A child class inherits everything from its parent and can add to it or override it. super() calls the parent's version:

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."
class Dog(Animal):
    def speak(self):             # override
        return f"{self.name} says Woof"

When the child needs extra constructor data, override __init__ and delegate the inherited setup:

class Dog(Animal):
    def __init__(self, name, trained=False):
        super().__init__(name)
        self.trained = trained

super() refers to the inherited implementation here. super().__init__(name) stores name via Animal; super().speak() would call Animal's speak method.

See it run

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

    def speak(self):
        return self.name + " makes a sound"

class Cat(Animal):
    def speak(self):
        return self.name + " says meow"

pet = Cat("Tom")
print(pet.speak())

Python looks for a method on the object's own class first, then on its parents.

Practice inheritance

Exercise 1

Add Cat(Animal): its __init__(self, name, indoor=True) calls super().__init__(name) and stores indoor, and speak() returns "Tom says Meow" for a cat named Tom.

Exercise 2

Keep Vehicle(name) with describe() returning name. Add Bicycle(Vehicle) accepting name and gears=1, initializing the parent via super and storing gears. Override describe to return NAME: N gears.

Exercise 3

Keep Ticket(base) with price() returning base. Add DiscountTicket(Ticket) taking base and percent, initializing the parent via super. Its price uses the parent's price minus that percentage, clamped to zero. Support discounts of 0, 100, and above 100. Repeated calls must not change base.

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest