Previous Lesson Current Lesson Next Lesson

Question 1

class Toy:
    def __init__(self, weight, price):
        self.weight = weight
        self.price = price


class Train(Toy):
    def make_sound(self):
        print("I go choo-choo!")

Because Train inherits from Toy, we do not need to duplicate the __init__ method in our implementation of Train. If we now do:

t = Train(5, 7.5)
print(t.price)
t.make_sound()

This will output:

7.5
I go choo-choo!

The Train class has inherited the weight and price attributes, which is why we can print the price of our newly created Train instance.

Question 2

class RareTrain(Train):
    def make_sound(self):
        print("I am a rare train that goes choo-choo!")

t = RareTrain(5, 7.5)
print(t.price)
t.make_sound()

This will output:

7.5
I am a rare train that goes choo-choo!

The RareTrain class has inherited the weight and price attributes from Toy via inheritance through the Train class. Finally, note that because we defined a custom make_sound method for RareTrain, it overrides the one defined for Train.