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):
self.name="Lena Headey"
def display(self):
print(self.name)
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):
print(self.s)
class B:
def __init__(self):
self.s="Winter is here!"
def display(self):
print(self.s)
A().display()
B().display()

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!”’.

Advertisements

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):
self.x=x
self.y=y
def __add__(self,o):
temp=myclass(self.x,o.x)
temp.x=self.x+o.x
temp.y=self.y+o.y
return temp
o1=myclass(3,4)
o2=myclass(6,7)
o3=o1+o2
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

References

Author: Srini

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