Python - Inheritance /
Polymorphism
There are three more important concepts in OOP
- Inheritance, makes the OOP code more
modular, easier to reuse and builds a
relationship between classes.
- Encapsulation, hiding some of the private
details of a class from other objects.
- Polymorphism allows using a common
operation in different ways.
Inheritance
Inheritance allows us to define a class that inherits
all the methods and attributes from another class.
The new class is child class, previous class is
parent class or superclass. The new class can access
all the attributes and methods from the superclass
by name. Inheritance builds a relationship between
the child class and parent class, usually in a way
that the parent class is a general type while the child
class is a specific type.
class Vehicle: Code demonstrates using inheritance:
first created base class Vehicle and it's
def __init__(self, name, color):
self.__name = name subclass Car. Car class have not
self.__color = color getName() method, but still able to
def getColor(self): access it, because the class Car
return self.__color inherits it from the Vehicle class. In
def setColor(self, color): the above code super() method is
self.__color = color used to call method of the base class.
def getName(self):
return self.__name
class Car(Vehicle):
def __init__(self, name, color, model):
# call parent constructor to set name and color
super().__init__(name, color)
self.__model = model
def getDescription(self):
return self.getName() + " " + self.__model + " in " +
self.getColor() + " color"
c = Car("Ford Mustang", "red", "GT350")
print(c.getDescription())
print(c.getName())
Multiple inheritance
class MySuperClass1():
def method_super1(self):
print("method_super1 method called")
class MySuperClass2():
def method_super2(self):
print("method_super2 method called")
class ChildClass(MySuperClass1,
MySuperClass2):
def child_method(self):
print("child method")
c = ChildClass()
ChildClass inherited MySuperClass1,
c.method_super1() MySuperClass2, object of ChildClass is now
c.method_super2() able to access method_super1() and
method_super2()
Example of polymorphism
Polymorphic len() function
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address":
"Nepal"}))
Many data type such as
string, list, tuple, set, and
dictionary can work with
the len() function. But
returns specific
information about specific
data types.
Class Polymorphism in Python
Polymorphism means the same function name
(but different signatures) being used for different
types. The key difference is the data types and
number of arguments used in function
Next code shows how Python can use two
different class types, in the same way. We create
a for loop that iterates through a tuple of objects.
Then call the methods without being concerned
about which class type each object is. We assume
that these methods actually exist in each class.
class Kazakhstan():
def capital(self):
print("Astana is the capital of Kazakhstan.")
def language(self):
print("Kazakh is primary language of Kazakhstan.")
def type(self):
print("Kazakhstan is a country with a developing
economy.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is an advanced economy.")
obj_kaz = Kazakhstan()
obj_usa = USA()
for country in (obj_kaz, obj_usa):
country.capital()
country.language()
country.type()
Polymorphism with Inheritance
In inheritance, the child class inherits the methods
from the parent class. However, it is possible to
modify a method in a child class that it has
inherited from the parent class. This is particularly
useful in cases where the method inherited from
the parent class doesn’t quite fit the child class. In
such cases, we re-implement the method in the
child class. This process of re-implementing a
method in the child class is known as Method
Overriding.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Implementing Polymorphism with a Function
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement
this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Wolf(Animal):
def speak(self):
return “UUUuuu"
# Create a list of Animal objects
animals = [Dog(), Cat(), Bird()]
# Call the speak method on each object
for animal in animals:
print(animal.speak())
Self training
Follow link:
Python Inheritance Quiz clck.ru/342Yeh
[https://pythongeeks.org/quizzes/python-inheritance-
quiz/]
Python-Polymorphism-Quiz clck.ru/342YpL
[https://www.i2tutorials.com/python-polymorphism-
quiz/]
• https://www.programiz.com/python-program
ming/polymorphism
• https://www.geeksforgeeks.org/polymorphis
m-in-python/
• https://thepythonguru.com/python-inheritan
ce-and-polymorphism/
• https://pythonnumericalmethods.berkeley.ed
u/notebooks/chapter07.03-Inheritance-Encap
sulation-and-Polymorphism.html
• https://www.packetcoders.io/python-
inheritance-vs-polymorphism/