Heavy-duty Usage Analysis of operators in Python, python Operators
This example describes how to use Operator Overloading in Python. We will share this with you for your reference. The details are as follows:
Class can overload python Operators
Operator Overloading makes our objects the same as those built in. The _ X _ name method is a special hook. python intercepts operators by using this special name to implement overloading. Python automatically calls this method when calculating operators, for example:
If the object inherits the _ add _ method, this method is called when it appears in the + expression. Through overloading, user-defined objects are like built-in objects.
Overload operators in Classes
1. Operator Overloading allows the class to intercept standard python operations.
2. classes can overload all python expression operators.
3. The class can overload object operations such as print, function call, and limitation.
4. Overload makes the instance of the class look more like built-in.
5. Overloading is implemented through special named class methods.
Method Name overload operation description call expression
_ Init _ constructor creation object: class ()
_ Del _ when the destructor releases an 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 value x [key] = value
_ Getslice _ slice x [low: high]
_ Len _ length len (x)
_ Cmp _ comparison x = Y, x <y
_ Radd _ operator on the right "+" non-instance + x
Example:
_ Getitem _ intercepts all index operations
>>> Class indexer: def _ getitem _ (self, index): return index ** 2 >>> x = indexer () >>> for I in range (5): print x [I] # x [I] Will call _ getitem _ (x, I) 014916