Python reload operators, python reload Operators

Source: Internet
Author: User
Tags bitwise operators

Python reload operators, python reload Operators

Some things make me uneasy, such as operator overloading. I decided not to support Operator overloading. This is my personal choice, because I have seen many C ++ programmers abuse it.

                                                -- James Gosling

Father of Java

 

Operator Overloading is used to enable user-defined objects to use infix operators (such as ++ and |) or unary operators (such as-and ~). In Python, function calling (), attribute access (.), and element access/slicing ([]) are also operators.

We briefly implement several operators for the Vector class. The _ add _ and _ mul _ methods are used to demonstrate how to use special methods to overload operators, but some minor problems are ignored. In addition, the Vector2d. _ eq _ method we define thinks that Vector (3, 4) = [3, 4] is True (True), which may not be reasonable.

 

Base on Operator Overloading

In some circles, the reputation of Operator Overloading is not good. This language feature may have been abused to confuse programmers and lead to defects and unexpected performance bottlenecks. However, if used properly, the API will become easy to use and the code will become easy to read. Python imposes some restrictions to balance flexibility, availability, and security:

  • Built-in operators cannot be reloaded.
  • You cannot create new operators. You can only reload existing
  • Some operators cannot be overloaded with -- is, and, or, and not (not bitwise operators
  • &, | And ~ Yes)

The previous blog has defined an infix operator for Vector, that is, =. This operator is supported by the _ eq _ method. We will improve the implementation of the _ eq _ method to better handle the operations that are not Vector instances. However, in terms of operator overloading, many comparison operators (= ,! =,>, <, >=, And <=) are special cases. Therefore, we will first reload four arithmetic operators in the Vector: unary operators-and +, and infix operators + and *.

 

Unary operator

-(_ Neg __)

A negative arithmetic operator is used for one element. If x is-2,-x = 2.

+ (_ Pos __)

Returns the positive arithmetic operator of a single element. Generally, x = + x, but there are some exceptions. If you are curious, read the notes "when x and + x are not equal.

~ (_ Invert __)

Bitwise inversion of integers, defined ~ X =-(x + 1 ). If x is 2, then ~ X =-3.

It is easy to support the unary operator. You only need to implement the corresponding special method. These special methods have only one parameter, self. Then, use the logical implementation that conforms to the class. However, a basic rule for operators must be followed: a new object is always returned. That is to say, you cannot modify self. You must create and return a new instance of the appropriate type.

For-and +, the result may be an instance of the same type as self. Most of the time, + returns a copy of self. The result of abs (...) is a scalar. However ~ It is hard to say what the result is reasonable because it may not be a bit of an integer. For example, in an ORM, the SQL WHERE clause should return the inverse set.

1 def _ abs _ (self): 2 return math. sqrt (sum (x * x for x in self) 3 4 def _ neg _ (self): 5 return Vector (-x for x in self) # In order to calculate-v, construct a new Vector instance and take every component of self against 6 7 def _ pos _ (self): 8 return Vector (self) # create a new Vector instance to calculate + v and input each component of self

When x and + x are not equal 

Everyone thinks x = + x, and in Python, this is true in almost all cases. However, I found two examples of x in the standard library! = + X.

The first example is related to the decimal. Decimal class. If x is a Decimal instance, it is created in the context of arithmetic operations, and then calculated in different contexts + x, then x! = + X. For example, the context where x is located uses a certain precision, and the accuracy changes when the calculation is + x, for example, the following

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.