Python Magic Method
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Program 1
#Magic(Dunder) Mehods in Python
class Employee:
def __init__(self,id,name,salary):
self.id=id
self.name=name
self.salary=salary
def __str__(self):
s="Emp ID: {} EMP Name: {} EMP Salary : {}"
s=s.format(self.id,self.name,self.salary)
return(s)
# def __repr__(self):
# s="Employee ID: {}Employee Name: {}Employee Salary : {}"
# s=s.format(self.id,self.name,self.salary)
# return(s)
def __call__(self):
s="Employee ID: {}Employee Name: {}Employee Salary : {}"
s=s.format(self.id,self.name,self.salary)
return(s)
#Calling
E=Employee(101,"Rajesh Verma",70000)
#print(E)
print(E()) # Object in method format
Program 2
# str="DataFlair Indore"
# print(len(str)) ## __len__() of String class
# class MyString:
# def __init__(self,s):
# self.s=s
# def __len__(self):
# x=0
# for i in self.s:
# x=x+1
# return(x)
# MS=MyString("Vivek Uprit DataFlair Indore")
# print(len(MS))
Program 3
# Operator Overloading with matgic method
# print(10+20) #Addtion
# print("Hello"+"Indore") #Concat
# print(10.5+20.5) # Addition
# print(True+True) #Addition
class Test:
def __init__(self,n):
self.n=n
def __add__(self,other):
return(self.n+other.n)
def __sub__(self,other):
return(self.n-other.n)
def __mul__(self,other):
return(self.n*other.n)
def __gt__(self,other):
if(self.n>other.n):
return True
else:
return False
def __ge__(self,other):
if(self.n>=other.n):
return True
else:
return False
def __lt__(self,other):
if(self.n<other.n):
return True
else:
return False
x=int(input("Enter First Number"))
y=int(input("Enter Second Number"))
T1=Test (x)
T2=Test(y)
if(T1<T2): # __lt__(T1,T2)
print("First No is small ")
else:
print("Second No is small ")
# if(T1>=T2): # __gt__(T1,T2)
# print("First No is grater")
# else:
# print("Second No is grater")
#print(T1+T2) # __add__(T1,T2)
#print(T1-T2) # __sub__(T1,T2)
#print(T1*T2)
# print(type(T1))
# print(type(T2))
# a=50
# b=20
# print(type(a))
# print(type(b))
# print(a+b)
Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

