python--operator overloading (important)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.