Magic Method in Python with Examples

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

class Student:
    def __init__(self,rno,name,course):
        self.rno=rno
        self.name=name
        self.course=course

    def __str__(self):
          s="Roll No of Student ={} , Name of Student ={} , Course of Student ={}"
          s=s.format(self.rno,self.name,self.course)
          return s

    def  __repr__(self):
          s="Roll No={} , Name={} , Course={}"
          s=s.format(self.rno,self.name,self.course)
          return s

    def __call__(self):
          print("Hello This is call method of class")     

S1=Student(101,"Vikas Sharma","Mtech")
print(S1)  
S1() 



Program 2

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
      

T1=Test(500)
T2=Test(300)

print(T1+T2)
print(T1-T2)
print(T1*T2)
if(T1>T2): 
      print("First Value is grater")
else:
      print("Second value is grater")
     
      
            









# class Student:
#     stname="Vivek"
#     def __len__(self):
#          x=0
#          for i in self.stname:
#                x+=1
#          return x               
# S1=Student()
# print(len(S1))

 

 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *