Back
+15 XP
Concept

Inheritance: Subclassing & Code Reuse

Subclass a parent class with `class Child(Parent):`. The child inherits every method and attribute from the parent automatically.

python
class Vehicle:
    def start(self):
        return "Engine running"

class Car(Vehicle):
    def honk(self):
        return "Beep beep!"

c = Car()
print(c.start())  # Inherited from Vehicle!
print(c.honk())   # Defined on Car!

# 1. Inheritance: Subclassing & Code Reuse Subclass a parent class with `class Child(Parent):`. The child inherits every method and attribute from the parent automatically: ```python class Vehicle: def start(self): return "Engine running" class Car(Vehicle): def honk(self): return "Beep beep!" c = Car() print(c.start()) # Inherited from Vehicle! print(c.honk()) # Defined on Car! ``` Unlike Java or TypeScript which require the `extends` keyword, Python simply places the parent class inside parentheses directly after the child class name.

Checkpoint

What syntax makes `RobotDog` inherit from `Robot`?

Practice

Create a base class `Device` with method `power_on(self)` returning `"ON"`. Create a subclass `Phone(Device)` with method `call(self)` returning `"Ring"`. Print both from a `Phone` instance.

Terminal
01
Tap code blocks below to assemble
Available Blocks