0% found this document useful (0 votes)
10 views

L03 Inheritance and Polymorphism

print("func2 in student 2.") Inheritance allows objects to share attributes and methods by arranging them in a hierarchy from general to specific. There are several types of inheritance including single, multi-level, hierarchical, multiple, and hybrid inheritance. Single inheritance refers to a child class extending a single parent class, while multi-level inheritance involves a grandparent, parent, and child relationship between classes.
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)
10 views

L03 Inheritance and Polymorphism

print("func2 in student 2.") Inheritance allows objects to share attributes and methods by arranging them in a hierarchy from general to specific. There are several types of inheritance including single, multi-level, hierarchical, multiple, and hybrid inheritance. Single inheritance refers to a child class extending a single parent class, while multi-level inheritance involves a grandparent, parent, and child relationship between classes.
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
You are on page 1/ 18

INHERITANCE 1

Inheritance is a way of arranging objects in a hierarchy from the most general to


the most specific.

You can often make many specific classes, by inheriting from a generic class:

§ attributes and methods are inherited

The more specific class is called the child


class or subclass, the generic class is called
the parent class, base class, or superclass.

Only what you want to add or change in


each specific class has to be
added/updated.
2

Inheritance can help us to represent


objects which have some differences and
some similarities in the way they work.

§ We can put all the functionality that the


objects have in common in a base class,
and then define one or more subclasses
with their own custom functionality.

Question: In this example,


§ Which attributes/functionalities are common?

§ Which attributes/functionalities are specific?


3

Inheritance is also a way of reusing


existing code easily.

§ If we already have a class which does


almost what we want, we can create a
subclass in which we partially override
some of its behaviour, or perhaps add
some new functionality.

§ When we declare the same method in child class which is already present in the
parent class, this is called method overriding.
example # Base class or Parent class L03-01.py 4
class Child:
# Constructor
Note that “Child” is the
def __init__(self, name): name of class.
self.name = name In the context of
Parent (Base or Super) Class # To get name inheritance, it is a
def getName(self): parent class, not a child
return self.name class .
# To check if this person is student
def isStudent(self):
return False

# Derived class or Child class


class Student(Child):
Child Class (Subclass) # True is returned
def isStudent(self):
return True
# An Object of Child (Base class)
std = Child("Alan")
print(std.getName(), std.isStudent())

# An Object of Student (Subclass)


std = Student("Mike")
print(std.getName(), std.isStudent())
Output:
Alan False
Mike True
TYPES OF INHERITANCE
5

There are four basic types of Inheritance:


Types of inheritance: Single Inheritance 6

Single Inheritance (Simple Inheritance) # Base class


class Parent:
L03-02.py

refers to a child and parent class def func1(self):


print("func1 in parent class.")
relationship where a class extends
# Derived class
another class. class Child(Parent):
def func2(self):
print("func2 in child class.")

object = Child()

object.func1()
object.func2()

Output:

func1 in parent class.


func2 in child class.
Types of inheritance: Multi-level Inheritance 7
class GrandParent: # Base class L03-03.py
def __init__(self, gpname):
Multilevel inheritance refers to a self.gpname = gpname

child and parent class relationship class Parent(GrandParent):


def __init__(self, pname, gpname):
# Intermediate class

where a class extends the child self.pname = pname


# invoking constructor of GrandParent class
class. GrandParent.__init__(self, gpname)

class Child(Parent): # Derived class


def __init__(self, name, pname, gpname):
self.name = name
# invoking constructor of Parent class
Parent.__init__(self, pname, gpname)

def print_name(self):
print('GrandParent name:', self.gpname)
print("Parent name:", self.pname)
print("Child name:", self.name)

s1 = Child('Lola', 'Emma', 'Charlotte')


s1.print_name()

Output:
GrandParent name: Charlotte
Parent name: Emma
Child name: Lola
Types of inheritance: Hierarchical Inheritance 8

# Base class L03-04.py

Hierarchical inheritance refers to a class Parent:


def func(self):
child and parent class relationship print(“func in parent class.")

where more than one classes # Derived class1


class Child1(Parent):
extends the same class. def func1(self):
print(“func1 in child 1.")

# Derived class2
class Child2(Parent):
def func2(self):
print("func2 in child 2.")

object1 = Child1()
object2 = Child2()
object1.func()
object1.func1()
object2.func()
object2.func2()

Output:
func in parent class.
func1 in child 1.
func in parent class.
func2 in child 2.
Types of inheritance: Multiple Inheritance 9

# Base class1 L03-05.py

Multiple Inheritance refers to the


class Mother:
mothername = ""

concept of one class extending more def mother(self):


print(self.mothername)
than one classes, which means a # Base class2
child class has more than one class Father:
fathername = ""
parents. def father(self):
print(self.fathername)

# Derived class
class Child(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)

obj = Child()
obj.fathername = "Stefan"
obj.mothername = "Emily"
obj.parents()

Output:
Father : Stefan
Mother : Emily
Types of inheritance: Hybrid Inheritance 10
class Person: L03-06.py
def func(self):
Hybrid inheritance refers to print("func in Person.")

combination of more than one type class Student1(Person):

of inheritance.
def func1(self):
print("func1 in student 1.")

class Student2(Person):
def func2(self):
print("func2 in student 2.")

class Student3(Student1, Student2):


def func3(self):
print("func3 in student 3.")

object = Student3()

object.func()
object.func1()
object.func2()
object.func3()

Output:
func in Person.
func1 in student 1.
func2 in student 2.
func3 in student 3.
BENEFITS OF INHERITANCE
11

1. Code reusability.

We do not have to write the same code again and again, we


can just inherit the properties we need in a child class.

2. It represents a real world relationship between parent


class and child class.

3. It is transitive in nature.

If a child class inherits properties from a parent class, then


all other sub-classes of the child class will also inherit the
properties of the parent class.
POLYMORPHISM 12

Polymorphism defines the ability to take multiple forms.

§ It refers to the use of a single type entity (method, operator or object) to


represent different types in different scenarios.
IMPLEMENTATION OF POLYMORPHISM IN PYTHON 13

Polymorphism can be implemented in Python in different ways:

§ with Function and Objects

§ with Classes Methods (Duck Typing)

§ with Inheritance

§ Operator Overloading
Polymorphism with Function and Objects 14

class Tomato(): L03-07.py

We can create a function that can def type(self):


print("Vegetable")
take any object, allowing for def color(self):
print("Red")
polymorphism.
class Apple():
def type(self):
§ In this example, the same function print("Fruit")
def color(self):
print("Green")
func() is used for two different
def func(obj):
objects. obj.type()
obj.color()

obj_tomato = Tomato()
obj_apple = Apple()

func(obj_tomato)
func(obj_apple)

Output:
Vegetable
Red
Fruit
Green
Polymorphism with Classes Methods (Duck typing) 15

In this type, Python uses two (or more) different class types in the same way.
§ The term ‘Duck Typing’ comes from the saying: “If it walks like a duck, and it
quacks like a duck, then it must be a duck.”
class Duck: L03-08.py

§ Duck typing is a concept related to def fly(self):


print("Duck flying")
dynamic typing, where the type or the class class Sparrow:
of an object is less important than the def fly(self):
print("Sparrow flying")
methods it defines. class Whale:
def swim(self):
§ When you use duck typing, you do not print("Whale swimming")

check types at all. Instead, you check for for animal in Duck(), Sparrow(), Whale():
animal.fly()
the presence of a given method or
Output:
attribute. Duck flying
Sparrow flying
AttributeError: 'Whale' object has no attribute 'fly'
Polymorphism with Inheritance 16

class Bird: L03-09.py

We can define functions in the derived def intro(self):


print("There are different types of birds.")
class that has the same name as the def flight(self):
functions in the base class. print("Most of the birds can fly but some cannot.")

class parrot(Bird):
§ We re-implement the functions in the def flight(self):
print("Parrots can fly.")
derived class.
class penguin(Bird):
def flight(self):
§ The phenomenon of re-implementing print("Penguins do not fly.")
a function in the derived class is obj_bird = Bird()
obj_parr = parrot()
known as Method Overriding. obj_peng = penguin()

obj_bird.intro()
obj_bird.flight() Output:
There are different types of birds.
obj_parr.intro()
Most of the birds can fly but some cannot.
obj_parr.flight() There are different types of birds.
Parrots can fly.
obj_peng.intro() There are different types of birds.
obj_peng.flight() Penguins do not fly.
Polymorphism with Operator Overloading 17

We can change the meaning of an class Point: L03-10.py

operator in Python depending upon def __init__(self, x=0, y=0):


self.x = x

the operands used. self.y = y

def __str__(self):
Example: return "({0},{1})".format(self.x, self.y)

def __add__(self, other):


§ 3 + 4 = 7 x = self.x + other.x
y = self.y + other.y
§ '3' + '4' = '34' return Point(x, y)

A = Point(1, 2)
§ (1,2) + (4,1) = ? B = Point(4, 1)

print(A + B)

Output:
(5,3)

P.S. This type of polymorphism will be discussed in more details in Lesson 11.
At the moment, a general understanding of the operator overloading is
18

You might also like