Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.2Inheritance in Python

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:

Python
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:

Python
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.

Python
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.

  1. Change the values assigned to the properties of the subclass and observe the output.
  2. Create a new subclass based on Animal and give it its own implementation of the act method.
  3. Modify the act method of the Cat class so that it displays a different message.
  4. 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.

Python
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.

Python
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.

Feedback 👍
Comments are sent via email to me.