[Go to site: main page, start]

0% found this document useful (0 votes)
3 views11 pages

Understanding Inheritance in Python

Uploaded by

queen licee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Understanding Inheritance in Python

Uploaded by

queen licee
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter Six: Inheritance in Python

Chapter six: Inheritance in python a hierarchy of classes, moving from the most
6.1 Chapter objectives general one to the most specific one.
By the end of this chapter, learners should be exhibit 6.3 Keys terms in inheritance
thorough understanding on how python implements the ▪ Child class
concept of inheritance This is a class that inherits properties and
characteristics from another class. Its also known
6.2 Introduction
One of the most important concepts in object-oriented as derived class or subclass.
programming is that of inheritance. It’s a concept of OOP ▪ parent class
which allows an object to derive properties and This refers to a class other classes acquire
characteristics (data and methods) from another object properties from. It’s also known as super class or
(class). In other terms, we can define inheritance as ability base class.
of a child class to acquire the properties (the data members) 6.4 Advantages of inheritance
The main advantages of inheritance are code
and functionality (the member methods) from parent class.
reusability and readability. When child class
A child class can also provide its specific implementation to
inherits the properties and functionality of parent
the functions of the parent class.
class, we need not to write the same code again in
child class. This makes it easier to reuse the code,
Through the concept, we can achieve hierarchical
makes us write the less code and the code becomes
classification. At the end, the programmer ends up building

1 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
much more readable. It also provides an opportunity to fast these functions in each of the three classes as shown
track implementation time. in below figure:
6.5 Examples of inheritance in real life
# example 1
Let’s assuming we have a class known as Human with height,
weight, colour etc as properties and eating (), sleeping (),
dreaming (), working() e.t.c as functionality.

Now we want to create Male and Female class, these classes


Its vivid clear that the above process results in
are different but since both Male and Female are humans,
duplication of same code 3 times increasing chances of
they share some common properties and behaviors
error and data redundancy. To avoid this type of
(functionality) so they can inherit those properties and
situation, we apply inheritance by creating a parent
functionality from Human class and rest can be written in
class known as Vehicle which contains these three
their class separately.
functions in it.
# example2
The other three class will inherit from the vehicle class
We consider a group of vehicles; Bus, Car and Truck. The
avoiding duplication of data as well as increasing code
methods/operations fuelAmount (), capacity(), applyBrakes()
reusability. We now model the new class as shown below
will be same for all of the three classes. If we create these
classes avoiding inheritance then we have to write all of

2 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
classes who can walk, talk and perform their special
skill as shown in the figure below.

Employing inheritance enables us to write the functions only one


For three classes, we need the same code for walk
time instead of three times as we have inherited rest of the three
and talk operations.
classes from base class (Vehicle).
If we wish to add a new feature e.g., eat, the same code
# example 3
has to be implemented for each class making the
Let’s assume we are working in solution consisting of three
program error prone as well as duplicating codes.
characters;maths teacher, footballer and a businessman.
To simplify the program, we can introduce a super
Since, all of the characters are persons, they can walk and talk.
class known as person which captures the common
However, they also have some special skills. A maths teacher
characteristics like talk, walk, eat, sleep but add
can teach maths, a footballer can play football and a
special skills to characteristics to the respective class
businessman can run a business. We individually create three
as shown below.

3 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
6.6 Implementing inheritance in python
We begin by creating the base class which is created just
like normal methods in python

To create a derived class in python which is inherited


from the base class we have to follow the below
syntax

Example: We create a class named Person with


Employing inheritance, we can have the same code. for walk name, height, width and gender as properties, and
and talk for each class. You just need to inherit them. a view Person as method:

For example, the Maths teacher (derived class), we inherit all


features of a Person (base class) and add a new feature
TeachMaths. The same applies for footballer and businessman
class.

The overall effect is having clean code which is understandable


and extendable.

4 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
class Person: 6.6.1 Create a Child Class
To create a class that inherits the functionality from
def __init__(self,name,w,h,g): another class, send the parent class as a parameter

[Link]=name when creating the child class. The following general


syntax is used
[Link]=w
class derived-class-name (base class):
[Link]=h
class body
[Link]=g
If a class inherits multiple classes, we mention each of
def viewPerson(self):
them by placing them inside the bracket. The following
print([Link],[Link],[Link],[Link]) syntax is applied Consider the following syntax.
Syntax
p=Person("Joe","62.5 Kgs","6 FT","Male")
class derive-class(<base class 1>, <base class 2>, .....
[Link]() <base class n>):

class body

5 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
Example, to create a class known as student which inherits the 6.6.2 Add the __init__() Function
We have now created a child class (student) that
above properties, we use the following statement in python
inherits the properties and methods from its parent
class Person: (person). We shall now proceed to implement the
def __init__(self, name, w, h, g): __init__() function to the child class which will replace
[Link] = name the pass keyword
[Link] = w
Always remember, this function is called
[Link] = h
automatically every time the class is instantiated
[Link] = g
def viewPerson(self): class Student(Person):
print([Link], [Link], [Link], [Link])
def __init__(self,name, w, h, g):
class Student(Person):
pass print("derived class")
s = Student("Joe", "62.5 Kgs", "6.2 FT", "Male")
When you add the __init__() function in the child class,
[Link]()
we will no longer inherit the parent's __init__() function.

You will notice class student has acquired properties


(attributes and behavior) from class person

6 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
To inherit __init__() function in the base class, we can add the By using the function, we do not have to use the name
following python code. of the parent element. All methods and properties shall
be automatically inherited from the parent class.

6.6.4 Adding properties to a child class


Let’s add registration number as a parameter

6.6.3 Use the super() Function


Python also has a super () function that will make the child
6.6.5 Adding method to a child class
class inherit all the methods and properties from its parent Let’s add new method known as viewRegno()

7 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
If you add a method in the child The syntax for single inheritance is as follows
class with the same name as a class subclass_name(base_class):
function in the parent class, the Class-body
inheritance of the parent method The following python program demonstrate the
will be overridden. concept of single inheritance
6.7 Types of inheritance Python class person:
Python supports five types of inheritance Single inheritance
def __init__(self):
(1), Multiple inheritance (2), Hierarchical inheritance (3),
[Link]=input("Enter the person name\n")
Multilevel inheritance (4) and Hybrid inheritance
class staff(person):
6.8.1 Single inheritance
In this type of inheritance, a class is allowed to inherit from def __init__(self):

only one class. i.e., one sub class is inherited by one base [Link]=input("Enter staff ID\n")

class only. super().__init__()


def printStaff(self):
print("Your name is\t"+ [Link]+ "and staff
Id\t" +[Link])
s=staff()
[Link]()

8 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python
6.8.2 Multiple Inheritance class person:
Multiple Inheritance is a feature of python where a class can def __init__(self):
inherit from more than one classes. i.e. one sub class inherits [Link]=input("Enter the person
from more than one base class. name\n")
class Department:
def __init__(self):
[Link]=input("Enter staff
department\n")
class staff(person,Department):
def __init__(self):
[Link]=input("Enter staff
number\n")
The Syntax is as follows person.__init__(self)
Department.__init__(self)
class subclass_name(base_class1, base_class2…base classn):
def viewStaff(self):
Class-body print([Link],[Link],[Link])
The number of base classes will be separated by a comma .A s=staff()
[Link]()
simple program that demonstrates multilevel inheritance is
given below
6.8.3 Multilevel inheritance
In this type of inheritance, a derived class is created
from another derived class.

9 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python

6.8.5 Hybrid (Virtual) Inheritance:


This type of inheritance is implemented by combining
more than one type of inheritance e.g. Combining

In the above example, class A inherits members of class B multilevel inheritance and Multiple Inheritance.

which itself is a derived class (derived from base class C). Below image shows the combination of hierarchical and

6.8.4 Hierarchical Inheritance multiple inheritance:


In hierarchical inheritance, we have one base class and more
than one child class. These child classes may or may not have
multiple child classes. All the child classes will
acquire/inherit the properties of the base class. This forms a
tree-like hierarchical structure as shown in the figure below

10 |D e v e l o p e d b y E d w a r d K i o k o
Chapter Six: Inheritance in Python

6.8.6 Additional programs


Consider the following example of a program that exhibits
multiple inheritance. The program has two base classes i.e.
person and grading. The properties of the two classes are
inherited by a third class know as student.

6.8 Chapter summary


6.9 Further reading suggestions

11 |D e v e l o p e d b y E d w a r d K i o k o

You might also like