Heavy-duty Usage Analysis of operators in Python, python Operators

Source: Internet
Author: User

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

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.