Class can overload Python's operator old knowledge: __x__ 's name is a system-defined name; it is a Python special method-specific identifier. 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, it is called when it appears in the + expression. By overloading, user-defined objects are like built-in. Overloading the operator 1 in the class, 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 specially named class method. Method name Overloaded operation description call expression __init__ Constructors Create objects: Class () __del__ destructors When objects are disposed __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__ Compare x = = Y, x < y__radd__ right operator "+" 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):p rint x[i] #x [i] will call __getitem__ (x,i) 014916
python--operator overloading (important)