Python operator overloading Usage instance analysis

Source: Internet
Author: User
The example in this article describes the Python operator overloading usage. Share to everyone for your reference. Specific as follows:

In the Python language, a C + +-like operator is provided with heavy functionality:

Here's how to call the Python operator again:

Method Overloads Call for
__init__ Constructor X=class ()
__del__ Destruction of destructor objects
__add__ + x+y,x+=y
__or__ | X| Y,x|=y
__repr__ Printing Conversion Print X,REPR (X)
__str__ Printing Conversion Print x,str (X)
__call__ Call Function X ()
__getattr_ Limit X.undefine
__setattr__ value X.any=value
__getitem__ Index X[key],
__len__ length len (X)
__cmp__ comparison X==y,x<>
__lt__ less than X<>
__eq__ equals X=y.
__radd__ Right-side + +x
__iadd__ + = X+=y
__iter__ iteration for in

1. Subtraction Overload

Class Number:    def __init__ (self, start):      Self.data = Start    def __sub__ (self, Other): #minus method      Return number (self.data-other) Number  = number (x)  y = number–10 # Invoke __sub__ method class number:   def __init__ (self, start):     Self.data = Start   def __sub__ (self, Other): #minus method     return number (Self.data-o ther) Number = number (x) y = number–10 # Invoke __sub__ method

2. Iterative overloading

Class Indexer:    def __getitem__ (self, Index): #iter override      Return index * * 2 X = indexer ()  x[2] for  i In range (5):    print X[i] class indexer:   def __getitem__ (self, Index): #iter override     Return index * * 2 X = Indexer () x[2] for I in range (5):   print X[i]

3. Index overloading

Class Stepper:    def __getitem__ (self, i):      return self.data[i]  X = Stepper ()  x.data = ' Spam ' x[1] #call __g etitem__  for item in X: #call __getitem__    Print Item class Stepper:   def __getitem__ (self, i):     return to self . data[i] X = Stepper () X.data = ' Spam ' x[1] #call __getitem__ for item in X: #call __getitem__    Print Item

4. Getattr/setattr Reload

Class Empty:def __getattr__ (self,attrname): if attrname = = ' age ': Return + else:raise Attribu      Teerror,attrname X = Empty () print X.age #call__getattr__ class Accesscontrol:def __setattr__ (self, attr, value):        if attr = = ' age ': # self.attrname = value loops! SELF.__DICT__[ATTR] = value Else:print attr raise Attributeerror, attr + ' not allowed ' X = accesscontr     OL () X.age = #call __setattr__ x.name = ' Wang ' #raise exception class Empty:def __getattr__ (self,attrname): if attrname = = ' age ': return else:raise attributeerror,attrname X = Empty () print X.age #call__getattr       __ Class Accesscontrol:def __setattr__ (self, attr, value): if attr = = ' age ': # self.attrname = value loops! SELF.__DICT__[ATTR] = value Else:print attr raise Attributeerror, attr + ' not allowed ' X = Accessco Ntrol () X.age = #call __setattr__ x.name = ' Wang ' #raise exception

5. Printing overloads

Class Adder:    def __init__ (self, value=0):      self.data = value    def __add__ (self, Other):      Self.data + = Other  class Addrepr (adder):    def __repr__ (self):      return ' Addrepr (%s) '% self.data  x = Addrepr (2) #run __ init__  x + 1    #run __add__  print x   #run __repr__ class adder:   def __init__ (self, value=0):     Self.data = value   def __add__ (self, Other):     Self.data + other class Addrepr (adder):   def __repr__ (self):     return ' Addrepr (%s) '% self.data x = Addrepr (2) #run __init__ x + 1    #run __add__ print x   #run __repr__

6. Call calling function overloading

Class Prod:    def __init__ (self, value):      self.value = value    def __call__ (self, Other):      return Self.value * other  P = Prod (2) #call __init__  print P (1) #call __call__  print P (2) class Prod:   def __init__ (self, Val  UE):     self.value = value   def __call__ (self, Other):     return self.value * Other p = Prod (2) #call __init__ Print P (1) #call __call__ print P (2)

7. Destructor Overloading

Class life:    def __init__ (self, name= ' name '):      print ' Hello ', name      self.name = name    def __del__ (self ):      print ' Goodby ', self.name  brain = Life (' brain ') #call __init__  brain = ' Loretta '  # call __del__

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.