Advanced use of mathematical operators in Python

WBOY
Release: 2016-07-21 14:53:13
Original
1394 people have browsed it

The behavior of an object in Python is determined by its type. The so-called type is to support certain specific operations. Numeric objects are fundamental elements in any programming language, supporting mathematical operations such as addition, subtraction, multiplication, and division.
Python's numerical objects include integers and floating point numbers, supporting various mathematical operations, such as +, -, *, /, etc. Without these operators, the program can only use function calls to perform mathematical operations, such as add(2, 3), sub(5, 2).
The functions of operators in the program are consistent with the usage of ordinary mathematical operations, making them 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 users implement the above special methods when defining their own classes, the objects of the custom class can support corresponding mathematical operations, thereby simulating the behavior of digital objects. This actually achieves the effect of operator overloading.

Here is an explanation of how to implement a Chinese number class that supports common mathematical operations in Python by implementing a Chinese number 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'零', u'一', u'二', u'三', u'四', 
      u'五', u'六', u'七', u'八', u'九', u'十']

  def __str__(self):
    sign = '负' 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__()

Copy after login

Currently, the effect achieved is as follows:

>>> a = ChineseNumber(2)
>>> a  #调用a.__repr__()
二
>>> print(a)  #调用a.__str__()

二

Copy after login

General mathematical operators
When defining a class, implement the __add__() method to add the + operator to this 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
Copy after login

At this time, the ChineseNumber object can use +.

>>> a, b = ChineseNumber(2), ChineseNumber(10)
>>> a + b
十二
>>> a + 5
七
>>> a + 3.7
TypeError: unsupported operand type(s) for +: 'ChineseNumber' and 'float'
Copy after login

For +, a + b is equivalent to calling a.__add__(b). Similarly, other mathematical operators can be defined, see the table below.

object.__add__(self, other): +
object.__sub__(self, other): -
object.__mul__(self, other): *
object.__matmul__(self, other): @
object.__truediv__(self, other): /
object.__floordiv__(self, other): //
object.__mod__(self, other): %
object.__divmod__(self, other): divmod, divmod(a, b) = (a/b, a%b)
object.__pow__(self, other[,modulo]): **, pow()
object.__lshift__(self, other): <<
object.__rshift__(self, other): >>
object.__and__(self, other): &
object.__xor__(self, other): ^
object.__or__(self, other): |
Copy after login

Mathematical operator with operand inversion (Reflected/Swapped Operand)

>>> 2 + a
TypeError: unsupported operand type(s) for +: 'int' and 'ChineseNumber'
Copy after login

2 is an integer type, and its __add__() method does not support objects of the ChineseNumber class, so the above error occurred. Defining mathematical operators with operand inversion can solve this problem. Add the __radd__() method to the ChineseNumber class to implement the + operation of operand reversal.

  def __radd__(self, other):
    return self.__add__(other)
Copy after login

For a + b, if a does not define the __add__() method, Python tries to call the __radd__() method of b. At this time, a + b is equivalent to calling b.__radd__(a).

>>> a = ChineseNumber(2)
>>> 2 + a
四
Copy after login

Similarly, other mathematical operators with operand inversion can be defined, see the table below.

object.__radd__(self, other): +
object.__rsub__(self, other): -
object.__rmul__(self, other): *
object.__rmatmul__(self, other): @
object.__rtruediv__(self, other): /
object.__rfloordiv__(self, other): //
object.__rmod__(self, other): %
object.__rdivmod__(self, other): divmod, divmod(a, b) = (b/a, b%a)
object.__rpow__(self, other[,modulo]): **, pow()
object.__rlshift__(self, other): <<
object.__rrshift__(self, other): >>
object.__rand__(self, other): &
object.__rxor__(self, other): ^
object.__ror__(self, other): |
Copy after login

Arithmetic assignment operator
The operation assignment operator uses a single operator to complete operation and 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
Copy after login

At this time,

>>> a, b = ChineseNumber(2), ChineseNumber(10)
>>> a += b
>>> a
十二
>>> a + 7
>>> a
十九
Copy after login

Similarly, other operation assignment operators can be defined, see the table below.

object.__iadd__(self, other): +=
object.__isub__(self, other): -=
object.__imul__(self, other): *=
object.__imatmul__(self, other): @=
object.__itruediv__(self, other): /=
object.__ifloordiv__(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): |=
Copy after login

Unary mathematical operators
Unary mathematical operators are operations with only one operand, such as the - operator for taking negative numbers. -The corresponding special function is __neg__(). Add __neg__() method for ChineseNumber,

  def __neg__(self):
    return ChineseNumber(-self.num)
Copy after login

At this time, the ChineseNumber object supports the - operation.

>>> a = ChineseNumber(5)
>>> -a
负五
Copy after login

See the table below for other unary operators.

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() 
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!