Python3 operator overload method example, python3 overload
Basic knowledge
In fact, "Operator Overloading" only means to intercept built-in operations in class methods ...... When an instance of the class appears in a built-in operation, Python automatically calls your method and the return value of your method becomes the result of the corresponding operation. The following is a review of key concepts of heavy load:
- Operator overload allows the class to intercept regular Python operations.
- Class can overload all Python expression Operators
- Class can be reloaded printing, function calls, vertex number operations and other built-in operations
- Overload makes the behavior of a class instance look like a built-in type.
- The overload is implemented through the class method with special names.
In other words, when a class provides a method with a special name, Python automatically calls the classes when their instances appear in their related expressions. As we have learned, the operator overload method is not mandatory and is generally not the default one. If you have not compiled or inherited an operator overload method, it only means that your class does not support corresponding operations. However, when used, these methods allow the class to simulate the interface of the built-in object, so the performance is more consistent.
The following code uses Python3.6.1 as an example:
Operator overload method: class calls a special syntax (len () by using the special name method (len (self ).
# Coding = UTF-8 # specialfuns. py operator overload method # class implements special syntax (len () by using the special name (_ len _ (self ()) class demo1: # constructor. when an object is instantiated, def _ init _ (self): print ("constructor") is called ") # destructor. when an object is recycled, def _ del _ (self): print ("destructor") # newclass demo2 (object ): # _ init _ called before, generally used to override the parent class _ new _ method, the specific use of meta-class code section (http://blog.csdn.net/rozol/article/details/69317339) def _ new _ (cls): print ("new") return object. _ new _ (Cls) # arithmetic operation class demo3: def _ init _ (self, num): self. data = num # + def _ add _ (self, other): return self. data + other. data #-def _ sub _ (self, other): return self. data-other. data # * def _ mul _ (self, other): return self. data * other. data #/def _ truediv _ (self, other): return self. data/other. data # // def _ floordiv _ (self, other): return self. data // other. data # % def _ mod _ (self, Other): return self. data % other. data # divmod () def _ divmod _ (self, other): # quotient (10/5), remainder (10% 5) return self. data/other. data, self. data % other. data # ** def _ pow _ (self, other): return self. data ** other. data # <def _ lshift _ (self, other): return self. data <other. data #> def _ rshift _ (self, other): return self. data> other. data # & def _ and _ (self, other): return self. data & other. da Ta # ^ def _ xor _ (self, other): return self. data ^ other. data # | def _ or _ (self, other): return self. data | other. dataclass none: def _ init _ (self, num): self. data = num # antiarithmetic operator (a + B. If a does not support Arithmetic Operators, search for Arithmetic Operators of B) (Note: Location conversion, + r before the original function name) class demo4: def _ init _ (self, num): self. data = num # + def _ radd _ (self, other): return other. data + self. data #-def _ rsub _ (self, other): return other. data-self. d Ata # * def _ rmul _ (self, other): return other. data * self. data #/def _ rtruediv _ (self, other): return other. data/self. data # // def _ rfloordiv _ (self, other): return other. data // self. data # % def _ rmod _ (self, other): return other. data % self. data # divmod () def _ rdivmod _ (self, other): return other. data/self. data, other. data % self. data # ** def _ rpow _ (self, other): return other. d Ata ** self. data # <def _ rlshift _ (self, other): return other. data <self. data #> def _ rrshift _ (self, other): return other. data> self. data # & def _ rand _ (self, other): return other. data & self. data # ^ def _ rxor _ (self, other): return other. data ^ self. data # | def _ ror _ (self, other): return other. data | self. data # Incremental Value assignment (Note: The position is the same as that of the original function, + I before the original function name) class demo5 (): def _ init _ (self, num ): Self. data = num # + = def _ iadd _ (self, other): return self. data + other #-= def _ isub _ (self, other): return self. data-other # * = def _ imul _ (self, other): return self. data * other #/= def _ itruediv _ (self, other): return self. data/other # // = def _ ifloordiv _ (self, other): return self. data // other # % = def _ imod _ (self, other): return self. data % other # ** = def _ ipow _ (self, other): Return self. data ** other # <= def _ ilshift _ (self, other): return self. data <other #> = def _ irshift _ (self, other): return self. data> other # & = def _ iand _ (self, other): return self. data & other # ^ = def _ ixor _ (self, other): return self. data ^ other # | = def _ ior _ (self, other): return self. data | other # comparison operator class demo6: def _ init _ (self, num): self. data = num # <def _ lt _ (sel F, other): return self. data <other. data # <= def _ le _ (self, other): return self. data <= other. data # = def _ eq _ (self, other): return self. data = other. data #! = Def _ ne _ (self, other): return self. data! = Other. data #> def _ gt _ (self, other): return self. data> other. data #> = def _ ge _ (self, other): return self. data> = other. data # unary operator class demo7: def _ init _ (self, num): self. data = num # + Positive def _ pos _ (self): return + abs (self. data) #-negative number def _ neg _ (self): return-abs (self. data) # abs () absolute value def _ abs _ (self): return abs (self. data )#~ Bitwise anti-def _ invert _ (self): return ~ Self. data # complex () character to number def _ complex _ (self): return 1 + 2j # int () to integer def _ int _ (self ): return 123 # convert float () to float def _ float _ (self): return 1.23 # round () approximate def _ round _ (self ): return 1.123 # format class demo8: # print () print def _ str _ (self): return "This is the demo. "# the string of the repr () object indicates def _ repr _ (self): return" This is a demo. "# bytes () object byte string representation def _ bytes _ (self): return B" This is One demo. "# format () format def _ format _ (self, format_spec): return self. _ str _ () # Attribute access class demo9: # obtain (nonexistent) attribute def _ getattr _ (self): print ("the accessed attribute does not exist ") # getattr () hasattr () obtain the attribute def _ getattribute _ (self, attr): print ("the accessed attribute is % s" % attr) return attr # setattr () set the property def _ setattr _ (self, attr, value): print ("set the % s property value to % s" % (attr, value) # delattr () delete attribute def _ delattr _ (self, attr): print ("Delete % S attribute "% attr) #===================================================== ===========================# Descriptor (Class (test1) the instance appears in the main class (runtest), these methods will be called) (Note: function call, these methods will not be called) class test1: def _ init _ (self, value = 1): self. value = value * 2 def _ set _ (self, instance, value): print ("set % s" % (self, instance, value )) self. value = value * 2 def _ get _ (self, instance, owner): print ("get % s" % (self, instance, owner) retu Rn self. value def _ delete _ (self, instance): print ("delete % s" % (self, instance) del self. valueclass test2: def _ init _ (self, value = 1): self. value = value + 0.3 def _ set _ (self, instance, value): print ("set % s" % (self, instance, value )) instance. t1 = value + 0.3 def _ get _ (self, instance, owner): print ("get % s" % (self, instance, owner )) return instance. t1 def _ delete _ (self, in Stance): print ("delete % s" % (self, instance) del self. valueclass runtest: t1 = test1 () t2 = test2 () # --- # custom propertyclass property_my: def _ init _ (self, fget = None, fset = None, fdel = None): self. fget = fget self. fset = fset self. fdel = fdel # The object is obtained (self itself, the instance calls this object (demo9), and the owner calls this object class Object (demo9 )) def _ get _ (self, instance, owner): print ("get % s" % (self, instance, owner) return se Lf. fget (instance) # def _ set _ (self, instance, value): print ("set % s" % (self, instance, value) self. fset (instance, value) # def _ delete _ (self, instance): print ("delete % s" % (self, instance) when the object is deleted )) self. fdel (instance) class demo10: def _ init _ (self): self. num = None def setvalue (self, value): self. num = value def getvalue (self): return self. num def delete (self): del self. num x = Property_my (getvalue, setvalue, delete) #===================================================== ===========================# custom container class lis: def _ init _ (self, * args): self. lists = args self. size = len (args) self. startindex = 0 self. endindex = self. size # len () number of container elements def _ len _ (self): return self. size; # lis [1] obtain the element def _ getitem _ (self, key = 0): return self. lists [key] # lis [1] = value sets the element def _ setitem __( Self, key, value): pass # del lis [1] Delete element def _ delitem _ (self, key ): pass # return iterator def _ iter _ (self): return self # rversed () reverse iterator def _ reversed _ (self): while self. endindex> 0: self. endindex-= 1 yield self [self. endindex] # next () iterator next element def _ next _ (self): if self. startindex> = self. size: raise StopIteration # control iterator end elem = self. lists [self. startindex] self. startindex + = 1 return elem # in /Not in def _ contains _ (self, item): for I in self. lists: if I = item: return True return False # yield generator (execute a return and continue executing the subsequent code to return) def yielddemo (): num = 0 while 1: #1 = True; 0 = False if num> = 10: raise StopIteration num + = 1 yield num # generator def yielddemo_1 (): while 1: num = yield print (num) # with Automatic context management class withdemo: def _ init _ (self, value): self. value = value # The value def _ en after the returned value is Ter _ (self): return self. value # data cleanup action def _ exit _ (self, exc_type, exc_value, traceback): del self. valueif _ name _ = "_ main _": # structure and analysis d1 = demo1 () del d1 # new d2 = demo2 () # Arithmetic Operator d3 = demo3 (3) d3_1 = demo3 (5) print (d3 + d3_1) print (d3-d3_1) print (d3 * d3_1) print (d3/d3_1) print (d3 // d3_1) print (d3% d3_1) print (divmod (d3, d3_1) print (d3 ** d3_1) print (d3 <d3_1) print (d3>> D3_1) print (d3 & d3_1) print (d3 ^ d3_1) print (d3 | d3_1) # Inverse Operator d4 = none (3) d4_1 = demo4 (5) print (d4 + d4_1) print (d4-d4_1) print (d4 * d4_1) print (d4/d4_1) print (d4 // d4_1) print (d4% d4_1) print (divmod (d4, d4_1) print (d4 ** d4_1) print (d4 <d4_1) print (d4> d4_1) print (d4 & d4_1) print (d4 ^ d4_1) print (d4 | d4_1) # Incremental Value assignment (comments to other codes during testing) d5 = demo5 (3) d5 <= 5 d5> = 5 d5 & = 5 d5 ^ = 5 d5 | = 5 d5 + = 5 d5-= 5 d5 * = 5 d5/= 5 d5 // = 5 d5 % = 5 d5 ** = 5 print (d5) # comparison operator d6 = demo6 (3) d6_1 = demo6 (5) print (d6 <d6_1) print (d6 <= d6_1) print (d6 = d6_1) print (d6! = D6_1) print (d6> d6_1) print (d6> = d6_1) # unary operator (comment other code during testing) d7 = demo7 (-5) num = + d7 num =-d7 num = abs (d7) num = ~ D7 print (num) print (complex (d7) print (int (d7) print (float (d7) print (round (d7) # format d8 = demo8 () print (d8) print (repr (d8) print (bytes (d8) print (format (d8, "") # Attribute access d9 = demo9 () setattr (d9, "a", 1) # => set the attribute value of a to 1 print (getattr (d9, "")) # => a/the access attribute is a print (hasattr (d9, "a") # => True/the access attribute is a delattr (d9, "") # Delete attribute a # --- d9.x = 100 # => set the x attribute value to 100 print (d9.x) # => x/the access attribute is x d El d9.x # => Delete x attributes # descriptor r = runtest () r. t1 = 100 #=><__ main __. test1> <__ main __. runtest & gt; 100 print (r. t1) # => 200/<__ main __. test1> <__ main __. runtest> <class '_ main __. runtest'> del r. t1 #=><__ main __. test1> <__ main __. runtest> r. t2 = 200 #=><__ main __. test2> <__ main __. runtest> 200/<__ main __. test1> <__ main __. runtest & gt; 200.3 print (r. t2) # => 400.6/<__ main __. test2> <__ main __. runtest> <class '_ Main __. runtest'>/<__ main __. test1> <__ main __. runtest> <class '_ main __. runtest'> del r. t2 # <__ main __. test2> <__ main __. runtest >#--- # custom property d10 = demo10 () d10.x = 100; #=><__ main __. property_my> <__ main __. demo10> 100 print (d10.x) # => 100/<__ main __. property_my> <__ main __. demo10> <class '_ main __. demo10'> del d10.x #=><__ main __. property_my> <__ main __. demo10> d10.num = 200; print (d 10. num) # => 200 del d10.num # custom container (Iterator) lis = lis (,) print (len (lis )) print (lis [1]) print (next (lis) for I in lis: print (I) for I in reversed (lis): print (I) print (3 in lis) print (7 in lis) print (3 not in lis) print (7 not in lis) # yield generator (Iterable object) for I in yielddemo (): print (I) # --- iters = iter (yielddemo () print (next (iters) print (Next (iters) # --- send data to the generator --- iters = yielddemo_1 () next (iters) iters. send (6) # send data and execute iters. send (10) # with Automatic context management with withdemo ("Less is more! ") As s: print (s)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.