Home >Backend Development >Python Tutorial >Detailed analysis of operator overloading usage in Python
The examples in this article describe the usage of operator overloading in Python. Share it with everyone for your reference, the details are as follows:
Classes can overload python operators
Operator overloading makes our objects the same as the built-in ones. The method named __X__ is a special hook, and python intercepts the operator through this special naming to achieve overloading. Python will automatically call such a method when calculating operators, for example:
If the object inherits the __add__ method, this method will be called when it appears in the + expression. Through overloading, user-defined objects behave like built-in ones.
Overloading operators in classes
1. Operator overloading enables classes to intercept standard python operations.
2. Classes can overload all python expression operators.
3. Classes can overload object operations: print, function call, qualification, etc.
4. Overloading makes class instances look more like built-in ones.
5. Overloading is achieved through specially named class methods.
Method name Overloaded operation instructions Call expression
__init__ Constructor Create object: class()
__del__ Destructor When releasing the object
__add__ “+” x + y
__or__ “|” x | y
__repr__ Printing, conversion Quote x.undefined
__getitem__ Index x[key], for loop, in test
__setitem__ Index assignment x[key] = value
__getslice__ Slices x[low:high]
__len__ Length len(x)
__cmp__ Compare x == Y , x < y
__radd__ The operator "+" on the right side Non-instance +
>>> class indexer: def __getitem__(self,index): return index ** 2 >>> x = indexer() >>> for i in range(5): print x[i] #x[i]将调用__getitem__(x,i) 0 1 4 9 16For more detailed analysis of operator overloading usage in Python and related articles, please pay attention to the PHP Chinese website!