'''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. '''
class myclass:
class_teacher = "sajita"
def __init__(self, aname, aage): # dunder method
self.name = aname
self.age = aage
def printdetails():
return (f"my name is {self.name} my age is {self.age} ")
def __add__(self, other): # dunder method
return self.age + other.age
def __truediv__(self, other): # dunder method
return self.age / other.age
def __repr__(self):
return (f"myclass('{self.name}',{self.age}) ")
def __str__(self):
return (f"my name is {self.name} my age is {self.age} ")
student1 = myclass("harish", 19)
student2 = myclass("virat", 32)
print(student1.name)
print(student1 + student2)
print(student1 / student2)
print(student2) # now this will print str method for printing repr method u have to write print(repr(student2)
print(repr(student2))
Comments
Post a Comment