Python - Operator Overloading

The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve "+" opertor for adding 2 objects.

Example 1: Add 2 objects using operator overloading

class example:
    def get(self, a):
        self.a=a

    def put(self):
        print("Result:",self.a)

    def __add__(self,ex2):
        ex4=example()
        ex4.a = self.a+ex2.a
        return ex4
    
ex1=example()
ex2=example()

ex1.get(int(input("Enter number")))
ex2.get(int(input("Enter number")))

ex3=example()
ex3=ex1+ex2
ex3.put()
class Result(Student, Marks): # Multiple inheritance
S.No Operator Magic Function
+ __add__(self, other)
- __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
** __pow__(self, other)
>= __ge__(self, other)
== __eq__(self, other)
!= __ne__(self, other)

Python - Method Overloading

Method Overloading means we can create multiple methods in a class with the same name but different arguments. Python does not support method overloading

Example 2: Perform method overloading with default arguments.

class example:
    def add(self, a=None, b=None, c=None):
        s=0
        if a!=None and b!=None and c!=None:
            s=a+b+c
        elif a!=None and b!=None:
            s=a+b
        else:
            s=a
        return s

ex1=example()
print(ex1.add(1))
print(ex1.add(1,2))
print(ex1.add(1,2,3))

Python - Method Overridding

Method Overridding means we can override method of base class into derived class. In Method overridding name and arguments of method is same.

Example 3: Perform method overridding

class A:
    def display(self):
        print("Class A - Display method")

Class B:
    def display(self):
        print("Class B - Display method")
a1=B()
a1.display()