Use advanced mathematical operators in Python

Source: Internet
Author: User
Tags unsupported
This article describes how to use advanced mathematical operators in Python, including basic knowledge such as assignment operators, for more information about object behavior in Python, see <g id = "1"> Type </g>. The so-called type is to support certain specific operations. Digital objects are basic elements in any programming language and support mathematical operations such as addition, subtraction, multiplication, and division.
Python numeric objects include integers and floating-point numbers. they support various mathematical operations, such as +,-, *, and. Without these operators, the program can only use the function call method for mathematical operations, such as add (2, 3), sub (5, 2 ).
The functions of operators in the program are the same as that of common mathematical operations, which is easier and more intuitive to use. In Python, these operators are implemented by defining some special methods of objects, such as object. _ add _ () and object. _ sub __(). If you implement the preceding special method when you define a class, you can enable the custom class object to support corresponding mathematical operations to simulate the behavior of a digital object. This actually achieves the effect of operator overloading.

The following describes how to implement a common mathematical operation in Python by implementing a Chinese numeric class that supports addition operations. The basic definition of the ChineseNumber class is as follows.

Class ChineseNumber: def _ init _ (self, n): self. num = n self. alphabet = [u '0', u '1', u '2', u '3', u '4', u '5', u '6 ', u '7', u '8', u '9', u '10'] def _ str _ (self): sign = 'negative 'if self. num <0 else ''return sign + ''. join ([self. alphabet [int (s)] for s in str (abs (self. num)]) def _ repr _ (self): return self. _ str __()

Currently, the effect is as follows:

>>> A = ChineseNumber (2) >>> a # Call. _ repr _ () 2> print (a) # Call. _ str _ () 2

General mathematical operators
When defining a class, implement the _ add _ () method to add a + operator to the class. Add the following method to ChineseNumber:

  def __add__(self, other):    if type(other) is ChineseNumber:      return ChineseNumber(self.num + other.num)    elif type(other) is int:      return ChineseNumber(self.num + other)    else:      return NotImplemented

Then the ChineseNumber object can be used +.

>>> A, B = ChineseNumber (2), ChineseNumber (10) >>> a + B 12 >>>> a + 5 7 >>> a + 3.7 TypeError: unsupported operand type (s) for +: 'chinanumber' and 'float'

For +, a + B is equivalent to calling a. _ add _ (B). Similarly, other mathematical operators can be defined. See the following table.

object.__add__(self, other): +object.__sub__(self, other): -object.__mul__(self, other): *object.__matmul__(self, other): @object.__truep__(self, other): /object.__floorp__(self, other): //object.__mod__(self, other): %object.__pmod__(self, other): pmod, pmod(a, b) = (a/b, a%b)object.__pow__(self, other[,modulo]): **, pow()object.__lshift__(self, other): <
 
  >object.__and__(self, other): &object.__xor__(self, other): ^object.__or__(self, other): |
 

Mathematical operators with reverse operands (Reflected/Swapped Operand)

>>> 2 + aTypeError: unsupported operand type(s) for +: 'int' and 'ChineseNumber'

2 is an integer. Its _ add _ () method does not support ChineseNumber objects, so the preceding error occurs. Defining mathematical operators that invert operands can solve this problem. Add the _ radd _ () method to the ChineseNumber class to implement the + operation of operand inversion.

  def __radd__(self, other):    return self.__add__(other)

For a + B, if a does not define the _ add _ () method, Python tries to call the _ radd _ () method of B. In this case, a + B is equivalent to calling B. _ radd _ ().

>>> A = ChineseNumber (2) >>> 2 + a 4

Similarly, you can define mathematical operators for the reversal of other operands, as shown in the following table.

object.__radd__(self, other): +object.__rsub__(self, other): -object.__rmul__(self, other): *object.__rmatmul__(self, other): @object.__rtruep__(self, other): /object.__rfloorp__(self, other): //object.__rmod__(self, other): %object.__rpmod__(self, other): pmod, pmod(a, b) = (b/a, b%a)object.__rpow__(self, other[,modulo]): **, pow()object.__rlshift__(self, other): <
 
  >object.__rand__(self, other): &object.__rxor__(self, other): ^object.__ror__(self, other): |
 

Operation value assignment operator
The operation value assignment operator uses a single operator to complete operations and value assignment operations. for example, a + = B is equivalent to calling a = a + B. Add the _ iadd _ () method to ChineseNumber to implement the + = operator.

  def __iadd__(self, other):    if type(other) is ChineseNumber:      self.num += other.num      return self    elif type(other) is int:      self.num += other      return self    else:      return NotImplemented

At this time,

>>> A, B = ChineseNumber (2), ChineseNumber (10) >>>> a + = B >>>> a 12 >>> a + 7 >>> a Nineteen

Similarly, other assignment operators can be defined, as shown in the following table.

object.__iadd__(self, other): +=object.__isub__(self, other): -=object.__imul__(self, other): *=object.__imatmul__(self, other): @=object.__itruep__(self, other): /=object.__ifloorp__(self, other): //=object.__imod__(self, other): %=object.__ipow__(self, other[,modulo]): **=object.__ilshift__(self, other): <<=object.__irshift__(self, other): >>=object.__iand__(self, other): &=object.__ixor__(self, other): ^=object.__ior__(self, other): |=

Unary mathematical operators
A mona1 mathematical operator is an operation that only has one operand, such as a negative number operator -. -The corresponding special function is _ neg __(). Add the _ neg _ () method to ChineseNumber,

  def __neg__(self):    return ChineseNumber(-self.num)

Now, the ChineseNumber object supports-operation.

>>> A = ChineseNumber (5) >>>-a minus five

For other unary operators, see the following table.

object.__neg__(self): -object.__pos__(self): +object.__abs__(self): abs()object.__invert__(self): ~object.__complex__(self): complex()object.__int__(self): int()object.__float__(self): float()object.__round__(self): round()object.__index__(self): operator.index() 

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.