7.3.1 Single Inheritance & Subclassing

Unit: Unit 7: Introduction to Classes • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Base Class (Parent)
class Vehicle:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

    def honk(self):
        return f"{self.brand} sounds horn: Beep beep!"

# Derived Class (Child inherits from Vehicle)
class Motorcycle(Vehicle):
    def wheelie(self):
        return f"{self.brand} is popping a wheelie!"

# Instantiate the child class
bike = Motorcycle("Ducati", 2024)

# Inherited method and attributes from Vehicle
print("Vehicle Brand:", bike.brand)
print(bike.honk())

# Specialized method from Motorcycle
print(bike.wheelie())

# Verify relationship
print("Is bike an instance of Motorcycle?", isinstance(bike, Motorcycle))
print("Is bike an instance of Vehicle?", isinstance(bike, Vehicle))
print("Is Motorcycle a subclass of Vehicle?", issubclass(Motorcycle, Vehicle))
Open in Live Interactive Python Sandbox →