Inheritance

Inheritance lets a new class reuse the attributes and methods of an existing class. The existing class is called the parent (or superclass); the new class is called the child (or subclass).

The is-a Relationship

Use inheritance when the child class is a type of the parent class. A Dog is an Animal. A SavingsAccount is a BankAccount.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."
class Dog(Animal):  # Dog inherits from Animal
    def speak(self):
        return "Woof"

The syntax class Dog(Animal): means Dog inherits everything from Animal.

Inherited Attributes and Methods

d = Dog("Rex")
print(d.name)    # → Rex  (from Animal.__init__)
print(d.speak()) # → Woof (overridden in Dog)
print(isinstance(d, Animal))  # → True
print(isinstance(d, Dog))     # → True
Rex
Woof
True
True

Dog automatically has __init__ from Animalbecause it does not define its own. The name attribute is set by Animal's constructor.

Method Overriding

When a child class defines a method with the same name as the parent, the child's version takes priority. This is called method overriding and is the foundation of polymorphism (covered in Lesson 12).

class Cat(Animal):
    def speak(self):
        return "Meow"
animals = [Dog("Rex"), Cat("Whiskers")]
for a in animals:
    print(f"{a.name}: {a.speak()}")
Rex: Woof
Whiskers: Meow

Your Task

  1. Write class Dog(Animal): below the Animal class
  2. Override speak(self) inside Dog to return "Woof"
  3. Do not write a new __init__ in Dog — let it inherit Animal's constructor so d.name still works
Section 1/4The is-a Relationship

The is-a Relationship

Use inheritance when the child class is a type of the parent class. A Dog is an Animal. A SavingsAccount is a BankAccount.

Inheritance

Inheritance lets a new class reuse the attributes and methods of an existing class. The existing class is called the parent (or superclass); the new class is called the child (or subclass).

The is-a Relationship

Use inheritance when the child class is a type of the parent class. A Dog is an Animal. A SavingsAccount is a BankAccount.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."
class Dog(Animal):  # Dog inherits from Animal
    def speak(self):
        return "Woof"

The syntax class Dog(Animal): means Dog inherits everything from Animal.

Output:

Click "Check" to run your code.