Lesson 11 of 15
Inheritance
Inheritance
Inheritance lets a class reuse and extend another class's behavior. The child class inherits all of the parent's methods and attributes.
Basic Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): # Dog inherits from Animal
def speak(self): # override parent method
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Rex")
dog.speak() # "Woof!"
dog.name # "Rex" (inherited attribute)
super()
Call the parent's __init__ to avoid repeating initialization code:
class Vehicle:
def __init__(self, make, speed):
self.make = make
self.speed = speed
class Car(Vehicle):
def __init__(self, make, speed, doors):
super().__init__(make, speed) # delegate to parent
self.doors = doors
isinstance() and issubclass()
isinstance(dog, Dog) # True
isinstance(dog, Animal) # True (Dog is an Animal)
issubclass(Dog, Animal) # True
Abstract Methods (abc)
The @abstractmethod syntax is a decorator — a function that wraps another function or method to modify its behavior. The @ symbol is shorthand: writing @abstractmethod above a method is equivalent to area = abstractmethod(area). Here, it marks area() as required — any subclass must override it or Python raises TypeError.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Your Task
Implement three classes:
Shapewith anarea()method that returns0Circle(Shape)that takesradiusand overridesarea()to returnπ * r²(use3.14159)Rectangle(Shape)that takeswidthandheightand overridesarea()
Pyodide loading...
Loading...
Click "Run" to execute your code.