The concept of inheritance is focused entirely on code reuse and maintainability of code.
Inheritance is a fundamental part of object-oriented design that allows one class (the subclass) to inherit attributes and methods of another class (the superclass).
Inheritance in Python
A cat is an animal, so we can define an Animal superclass as shown below:
class Animal: # An animal class type = "" name = "" def __init__(self, type, name): self.type = type self.name = name def act(self): print("Doing something") def getName(self): return self.name
Now, we can define a Cat class for our cat:
class Cat (Animal): # A cat class name = "" def __init__(self, name): self.type = "Cat" self.name = name def act(self): print("Meow")
Now in the same program, instantiating a new cat and using the act method on
the newly instantiated cat, we should get the word Meow on
the screen.
c = Cat("Gismo") c.act() print(c.getName())
This is simply overwriting the act method defined in the Animal superclass
with its own derivation of it and then utilising the getName method
from the superclass to get the name property of the instance.
- Change the values assigned to the properties of the subclass and observe the output.
- Create a new subclass based on
Animaland give it its own implementation of theactmethod. - Modify the
actmethod of theCatclass so that it displays a different message. - Create a second instance of a subclass and assign it different values.
Rewrite the program so that it defines a Dog class that inherits from Animal.
class Animal: def act(self): print("Doing something") class Dog(Animal): def act(self): print("Woof") d = Dog() d.act()
Modify the following program so that the subclass displays a different message when its act method is called.
class Animal: def act(self): print("Doing something") class Bird(Animal): def act(self): print("Chirp") b = Bird() b.act()
Extension challenge: Create a superclass called Vehicle containing a method called move. Create two subclasses, Car and Plane, that override the move method with their own behaviour.
