Python Oops Concept: How to Understand Quickly

Here are three python Oops examples that a programmer needs. Those are Inheritance, Polymorphism, and Overloading. Added notes under each example to know how it can be applied in projects.

1. Python: Single Inheritance Example

class Base:
def __init__(self):"Lena Headey"
def display(self):
class Derived(Base): #inherits from class, Base
def disp(self):
print("Derived method")
o=Derived() #Derived class object
o.display() #Base class method
o.disp() #Derived class method

This program consists of two classes, viz., ‘Base’ and ‘Derived’. The derived class inherits the base class properties through the statement ‘class Derived(Base):’.

This means that the methods and attributes of the class ‘Base’ can be accessed through an instance of class ‘Derived’. Check out 4 Top Python Oops Concepts Simplify Your Coding.

2. Python Polymorphism Example

Method Overriding

class A:
def __init__(self):
self.s="Winter is coming!"
def display(self):
class B:
def __init__(self):
self.s="Winter is here!"
def display(self):

The method ‘display()’ is overloaded in a different way. The method is not defined twice but still performs different functions in two different situations.

The argument list of the method ‘display(‘) contains a statement, ‘x=”winter is coming!”’.


This essentially means that in the absence of an argument in the calling method object, x will contain the string, “winter is coming!” by default.

In case an explicit argument is passed while invoking the method, the variable x will no longer contain the default value.

Instead, it will hold the value passed in the argument while invoking a method.

3. Python Overloading Example

Operator Overloading

class myclass:
def __init__(self,x,y):
def __add__(self,o):
return temp
print("o1.x= ",o1.x," o1.y= ",o1.y)
print("o2.x= ",o2.x," o2.y= ",o2.y)
print("After adding o1 and o2:")
print("o3.x= ",o3.x," o3.y= ",o3.y)

The operator, ’+’ is overloaded by redefining the ‘__add__()’method that adds the values stored in two objects and returns an object of similar type. Here is Basic Python Oops Concepts.

It is important to note that the first operand, ‘o1’, invokes the ‘__add__()’ method and the instance, ‘o2’, is passed as a reference to this method.

The returned object is stored in ‘o3’, which is then used to access the added results.

Related Posts


Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.