Operator Overloading | polymorphism
Operator Overloading | Polymorphism
Operator overloading in Python is the ability of a single operator to perform more than one operation based on the class (type) of operands. For example, the + operator can be used to add two numbers, concatenate two strings or merge two lists.
Output
Output
Output
a = 5
b = 6
print(a + b)
print(int.__add__(a,b))
11 11Addition of two student marks
class Student:
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
def __add__(self, other):
m1 = self.m1 + other.m1
m2 = self.m2 + other.m2
s3 = Student(m1,m2)
return s3
s1 = Student(34, 64)
s2 = Student(43, 64)
s3 = s1 + s2
print(s3.m1)
# s3 = s1 + s2 -> Student.__add__(s1,s2)
77greater than marks
class Student:
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
def __gt__(self, other):
r1 = self.m1 + self.m2
r2 = self.m1 + self.m2
if r1 > r2:
return True
else:
return False
s1 = Student(34, 64)
s2 = Student(43, 64)
if s1 > s2:
print("s1 win")
else:
print("s2 win")
s2 win
Post a Comment