Motivation

After having written some notes on the four pillars of OOP, I did not quite understand what inheritance means. Decided to explore examples and finally understood it better.

The gist

  • Inheritance enables creating a new class using attributes and methods of an existing class.
  • The class from which attributes and methods are inherited from is called the superclass.
  • The class which inherits the attributes and methods from the superclass is called the subclass.

This note will only talk about single inheritance. Multiple inheritance next time?

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# superclass
class Bird:

def __init__(self):
print("Bird is ready")

def whoisThis(self):
print("Bird")

def swim(self):
print("Swim faster")

# subclass

# notice how the Bird class is inherited
class Penguin(Bird):

def __init__(self):

# use of super() is possible here!
Bird.__init__(self)
print("Penguin is ready")

def whoisThis(self):
print("Penguin")

def run(self):
print("Run faster")

### OUTPUT TEST ###
peggy = Penguin() # prints "Bird is ready" and "Penguin is ready". This shows inheritance of the Bird class. BUT

peggy.whoisThis() # prints "Penguin" but not "Bird". Same method name so the Penguin method overrides that of Bird.

References

  1. Python Inheritance Example
  2. Python Object Oriented Programming