0% found this document useful (0 votes)
4 views7 pages

Understanding Method Overriding in Python

Method overriding allows a subclass to provide a specific implementation of a method from its superclass. The version of the method executed depends on the object type used to invoke it, and it can occur in scenarios like multiple and multilevel inheritance. Additionally, Python supports calling parent class methods within overridden methods using either the class name or the super() function.

Uploaded by

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

Understanding Method Overriding in Python

Method overriding allows a subclass to provide a specific implementation of a method from its superclass. The version of the method executed depends on the object type used to invoke it, and it can occur in scenarios like multiple and multilevel inheritance. Additionally, Python supports calling parent class methods within overridden methods using either the class name or the super() function.

Uploaded by

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

Method overriding

Method overriding is an ability of any object-oriented programming language that allows a


subclass or child class to provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes. When a method in a subclass has the
same name, same parameters or signature and same return type(or sub-type) as a method in
its super-class, then the method in the subclass is said to override the method in the super-
class.

The version of a method that is executed will be determined by the object that is used to
invoke it. If an object of a parent class is used to invoke the method, then the version in the
parent class will be executed, but if an object of the subclass is used to invoke the method,
then the version in the child class will be executed. In other words, it is the type of the
object being referred to (not the type of the reference variable) that determines which
version of an overridden method will be executed.
Example:

# Python program to demonstrate method overriding Defining parent class


class Parent():
# Constructor
def __init__(self):
[Link] = "Inside Parent"

# Parent's show method


def show(self):
print([Link])

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
[Link] = "Inside Child"
# Child's show method
def show(self):
print([Link])

# Driver's code
obj1 = Parent()
obj2 = Child()

[Link]()
[Link]()

Output:
Inside Parent
Inside Child
Method overriding with multiple and multilevel inheritance
1. Multiple Inheritance: When a class is derived from more than one base class it is
called multiple Inheritance.
Example: Let’s consider an example where we want to override a method of one parent
class only. Below is the implementation.

# Python program to demonstrate


# overriding in multiple inheritance

# Defining parent class 1


class Parent1():

# Parent's show method


def show(self):
print("Inside Parent1")

# Defining Parent class 2


class Parent2():

# Parent's show method


def display(self):
print("Inside Parent2")

# Defining child class


class Child(Parent1, Parent2):

# Child's show method


def show(self):
print("Inside Child")

# Driver's code
obj = Child()
[Link]()
[Link]()

Output:
Inside Child
Inside Parent2

2. Multilevel Inheritance: When we have a child and grandchild relationship.


Example: Let’s consider an example where we want to override only one method of one of
its parent classes. Below is the implementation.

# Python program to demonstrate overriding in multilevel inheritance

class Parent():

# Parent's show method


def display(self):
print("Inside Parent")

# Inherited or Sub class (Note Parent in bracket)


class Child(Parent):

# Child's show method


def show(self):
print("Inside Child")

# Inherited or Sub class (Note Child in bracket)


class GrandChild(Child):

# Child's show method


def show(self):
print("Inside GrandChild")

# Driver code
g = GrandChild()
[Link]()
[Link]()

Output:
Inside GrandChild
Inside Parent

Calling the Parent’s method within the overridden method


Parent class methods can also be called within the overridden methods. This can generally
be achieved by two ways.
 Using Classname: Parent’s class methods can be called by using the
Parent [Link] inside the overridden method.
Example:
# Python program to demonstrate calling the parent's class method inside the overridden method

class Parent():

def show(self):
print("Inside Parent")

class Child(Parent):

def show(self):

# Calling the parent's class


# method
[Link](self)
print("Inside Child")

# Driver's code
obj = Child()
[Link]()

Output:
Inside Parent
Inside Child

 Using Super(): Python super() function provides us the facility to refer to the parent class
explicitly. It is basically useful where we have to call superclass functions. It returns the
proxy object that allows us to refer parent class by ‘super’.
Example 1:

# Python program to demonstrate calling the parent's class method inside the overridden
# method using super()

class Parent():

def show(self):
print("Inside Parent")

class Child(Parent):

def show(self):

# Calling the parent's class


# method
super().show()
print("Inside Child")

# Driver's code
obj = Child()
[Link]()
Output:
Inside Parent
Inside Child

Python Override Method


A subclass may change the functionality of a Python method in the
superclass. It does so by redefining it.
Method Overriding Example.
>>> class A:
def sayhi(self):
print("I'm in A")
>>> class B(A):
def sayhi(self):
print("I'm in B")

>>> bobj=B()
>>> [Link]()
Output
I’m in B

Python Method Overloading


>>> def add(a,b):
return a+b
>>> def add(a,b,c):
return a+b+c
>>> add(2,3)
Output
Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module> add(2,3)
TypeError: add() missing 1 required positional argument: ‘c’
This code doesn’t make a call to the version of add() that takes in two
arguments to add. So we find it safe to say Python doesn’t support method
overloading.
However, we recently ran into a rather Pythonic way to make this happen.
Check this out:
>>> def add(instanceOf,*args):
if instanceOf=='int':
result=0
if instanceOf=='str':
result=''
for i in args:
result+=i
return result
In this code, not only do we use the *args magic variable for variable
arity, we also let the code deal with both integers and strings.
Watch it happen:
>>> add('int',3,4,5)
Output
12
>>> add('str','I ','speak ','Python')
Output
‘I speak Python’
You say what if I do this?:
>>> def add(a,b,c=0):
Output
return a+b+c
>>> add(2,3)
Output
5

To that, we’ll say this isn’t method overloading, this is simply used of
default arguments.

Operator Overloading means giving extended meaning beyond their


predefined operational meaning. For example operator + is used to add two
integers as well as join two strings and merge two lists. It is achievable
because ‘+’ operator is overloaded by int class and str class. You might have
noticed that the same built-in operator or function shows different behavior for
objects of different classes, this is called Operator Overloading.
Example
# Python program to show use of + operator for different purposes.

print(1 + 2)

# concatenate two strings


print("Welcome"+"CHITKARA")

# Product two numbers


print(3 * 4)

# Repeat the String


print("CHITKARA"*4)
Output
3
WelcomeCHITKARA
12
CHITKARACHITKARACHITKARACHITKARA

isinstance() method

isinstance() is a built-in Python function that checks whether an object or variable is an


instance of a specified type or class (or a tuple of classes), returning True if it matches and
False otherwise, making it useful for type-checking and ensuring safe operations in
dynamic code. Example:

x = 10
print(isinstance(x, int)) # x is int

class Animal:
pass

dog = Animal()
print(isinstance(dog, Animal)) # dog is Animal

Output
True
True

Explanation:
isinstance(x, int) returns True as x is an integer.
isinstance(dog, Animal) returns True as dog is an instance of the Animal class.

You might also like