This example describes the use of operator overloading in Python. Share to everyone for your reference, as follows:
Class can overload Python's operators
Operator overloading makes our objects the same as built-in. The method of __x__ 's name is a special hook, and Python intercepts the operator with this special name to implement overloading. Python automatically calls such a method when it calculates an operator, for example:
If the object inherits the __add__ method, this method is called when it appears in the + expression. By overloading, user-defined objects are like built-in.
Overloading operators in a class
1. Operator overloading allows the class to intercept standard Python operations.
2. Classes can overload all Python's expression operators.
3. Classes can overload object operations: Print, function call, qualification, etc.
4. Overloading makes instances of classes look more like built-in.
5, overloading is implemented by a special named class method.
Operation Description of method name overloading call expression
__init__ constructor Creation object: Class ()
__del__ when the destructor releases the object
__add__ "+" x + y
__or__ "|" x | Y
__repr__ print, convert print x, ' x '
__call__ function call X ()
__getattr__ Property Reference x.undefined
__getitem__ index x[key],for loop, in test
__setitem__ index Assignment X[key] = value
__getslice__ Shard X[low:high]
__len__ length len (x)
__cmp__ comparison x = = y, x < y
__radd__ operator "+" non-instance + X on right
Example:
__GETITEM__ intercepts all index operations
>>> class Indexer:def __getitem__ (self,index): Return index * * 2>>> x = indexer () >>> for i in RA Nge (5):p rint x[i] #x [i] will call __getitem__ (x,i) 014916