Skip to the content.

Inheritance

-

What Is Inheritance?

Inheritance is the ability to define a new class that is a modified version of an existing class.

-

How Does It Work?

class BaseClass:
    pass

class DerivedClass(BaseClass):
    pass

-

Create Base Class

Let’s start by defining a base class called Mammal and one called Bird.

class Mammal:
    pass

class Bird:
    def sing(self):
        print("la la la")
    
    def fly(self):
        print("flying is great")

-

Create Derived Classes

We can use the the Bird base class to define new classes that derive from Bird.
Let’s define a Hawk class and a Penguin class.

class Hawk(Bird):
    def sing(self): # overrides sing method from base class
        print("screech")
    
    def attack(self): # custom functionality not provided from base class
        print("swoosh")
    
class Penguin(Bird):
    def fly(self): # overrides sing method from base class
        print("Sorry to disappoint.")
    
    def swim(self): # custom functionality not provided from base class
        print("splish splash")

-

Leveraging Inheritance

redwing = Hawk()
redwing.sing() # Exists in Hawk class so this is the method that will be invoked.
# screech

redwing.fly() # Does not exist in Hawk class but exists in the base class Bird. 
# flying is great
tux = Penguin()
tux.fly() # Exists in the Penguin class so this is the method that will be invoked.
# Sorry to disappoint.

tux.sing() # # Does not exist in Penguin class but exists in the base class Bird. 
# la la la

-

isinstance

The isinstance() builtin function can be used to check an instance’s type.

isinstance(redwing, Hawk)
# True
isinstance(redwing, Bird)
# True

isinstance(tux, Hawk)
# False
isinstance(tux, Penguin)
# True
isinstance(tux, Bird)
# True

-

issubclass

The issubclass() builtin function can be used to check class inheritance.

issubclass(Hawk, Bird)
# True
issubclass(Penguin, Bird)
# True

issubclass(Hawk, Mammal)
# False
issubclass(Bird, Mammal)
# False

-

Multiple Inheritance

-

What Is It?

Multiple Inheritance simply means that a class can be derived from more than one base class.

-

How Does It Work?

class BaseClassA:
    pass

class BaseClassB:
    pass

# A class definition with multiple base classes
class DerivedClass(BaseClassA, BaseClassB):
    pass

-

Create a Base Class

class BirdOfPrey:
    def attack(self):
        print("swoosh")
    
    def tear_flesh(self):
        print("tearing flesh... look away.")

-

Create Derived Classes

class Hawk(Bird, BirdOfPrey):
    def sing(self): # overrides sing method from base class Bird.
        print("screech")

-

Leveraging Multiple Inheritance

redwing = Hawk()

redwing.fly() # Does not exist in Hawk class but exists in base class Bird.
# flying is great

redwing.tear_flesh() # Does not exist in Hawk class but exists in the base class BirdOfPrey. 
# tearing flesh... look away.

-

The End

Parrot