operator — 作为函数的标准运算符

源代码: Lib/operator.py


The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y . Many function names are those used for special methods, without the double underscores. For backward compatibility, many of these have a variant with the double underscores kept. The variants without the double underscores are preferred for clarity.

The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations.

The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:

运算符。 lt ( a , b )
运算符。 le ( a , b )
运算符。 eq ( a , b )
运算符。 ne ( a , b )
运算符。 ge ( a , b )
运算符。 gt ( a , b )
运算符。 __lt__ ( a , b )
运算符。 __le__ ( a , b )
运算符。 __eq__ ( a , b )
运算符。 __ne__ ( a , b )
运算符。 __ge__ ( a , b )
运算符。 __gt__ ( a , b )

Perform “rich comparisons” between a and b . Specifically, lt(a, b) 相当于 a < b , le(a, b) 相当于 a <= b , eq(a, b) 相当于 a == b , ne(a, b) 相当于 a != b , gt(a, b) 相当于 a > b and ge(a, b) 相当于 a >= b . Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See 比较 for more information about rich comparisons.

The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations:

运算符。 not_ ( obj )
运算符。 __not__ ( obj )

Return the outcome of not obj . (Note that there is no __not__() method for object instances; only the interpreter core defines this operation. The result is affected by the __bool__() and __len__() methods.)

运算符。 truth ( obj )

返回 True if obj 为 True,和 False 否则。这相当于使用 bool 构造函数。

运算符。 is_ ( a , b )

返回 a is b 。测试对象身份。

运算符。 is_not ( a , b )

返回 a is not b 。测试对象身份。

The mathematical and bitwise operations are the most numerous:

运算符。 abs ( obj )
运算符。 __abs__ ( obj )

返回绝对值的 obj .

运算符。 add ( a , b )
运算符。 __add__ ( a , b )

返回 a + b , for a and b numbers.

运算符。 and_ ( a , b )
运算符。 __and__ ( a , b )

Return the bitwise and of a and b .

运算符。 floordiv ( a , b )
运算符。 __floordiv__ ( a , b )

返回 a // b .

运算符。 index ( a )
运算符。 __index__ ( a )

返回 a converted to an integer. Equivalent to a.__index__() .

3.10 版改变: The result always has exact type int . Previously, the result could have been an instance of a subclass of int .