Let’s now look at a feature allowed by Python called multiple inheritance. As you may have guessed from the name, this is when a subclass inherits from more than one superclass. One form of multiple inheritance is when there are multiple levels of inheritance. This means a class inherits members from its superclass and its super-superclass.
class Animal: def __init__(self, name): self.name = name def say_hi(self): print("{} says, Hi!".format(self.name)) class Cat(Animal): pass class Angry_Cat(Cat): pass my_pet = Angry_Cat("Mr. Cranky") my_pet.say_hi() # Mr. Cranky says, Hi!
In the above example, Angry_Cat
inherits from Cat
and Cat
inherits from Animal
. Both Angry_Cat
and Cat
have access to the Animal
class name
attribute and .say_hi()
method. Any feature added to Cat
, Angry_Cat
will also have access to.
Instructions
Managers decide to start walking around more to let people know who is in charge.
Inside script.py:
- Define a
Manager
class and have it inherit from theAdmin
class - Inside the
Manager
class, define a methodsay_id()
that outputs that they are in charge.
The Managers want to set a good example so they also let people know their ID and that they are an admin.
Inside the .say_id()
method of Manager
:
- Call the
Admin
class.say_id()
method
Now test it out.
At the bottom of script.py:
- Define a variable
e4
and set it to an instance of theManager
class - Call the
.say_id()
method of the instance ine4
Now you will get output from all 3 classes.