简介
operator模块提供了一套与Python的内置运算符对应的高效率函数。 许多函数名与特殊方法名相同,只是没有双下划线。为了向后兼容性,也保留了许多包含双下划线的函数。为了表述清楚,建议使用没有双下划线的函数。
函数包含的种类有:对象的比较运算、逻辑运算、数学运算以及序列运算。
源代码: Lib/operator.py
1 | >>> import operator |
对象比较函数
对象比较函数适用于所有的对象,函数名根据它们对应的比较运算符命名。
1 | operator.lt(a, b) # a < b |
逻辑运算
1 | operator.not_(obj) |
赋值运算
1 | operator.iadd(a, b) |
数学运算
1 | operator.abs(obj) |
序列运算
1 | operator.concat(a, b) |
实用函数
operator.attrgetter
1 | operator.attrgetter(attr) |
Equivalent to:
1 | def attrgetter(*items): |
operator.itemgetter
1 | operator.itemgetter(item) |
Equivalent to:
1 | def itemgetter(*items): |
The items can be any type accepted by the operand’s __getitem__()
method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice:
1 | >>> itemgetter(1)('ABCDEFG') |
Example of using itemgetter() to retrieve specific fields from a tuple record:
1 | >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] |
operator.methodcaller
1 | operator.methodcaller(name[, args...]) |
Equivalent to:
1 | def methodcaller(name, *args, **kwargs): |
Mapping Operators to Functions
This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the operator module.
Operation | Syntax | Function |
---|---|---|
Addition | a + b |
add(a, b) |
Concatenation | seq1 + seq2 |
concat(seq1, seq2) |
Containment Test | obj in seq |
contains(seq, obj) |
Division | a / b |
truediv(a, b) |
Division | a // b |
floordiv(a, b) |
Bitwise And | a & b |
and_(a, b) |
Bitwise Exclusive Or | a ^ b |
xor(a, b) |
Bitwise Inversion | ~ a |
invert(a) |
Bitwise Or | `a | b` |
Exponentiation | a ** b |
pow(a, b) |
Identity | a is b |
is_(a, b) |
Identity | a is not b |
is_not(a, b) |
Indexed Assignment | obj[k] = v |
setitem(obj, k, v) |
Indexed Deletion | del obj[k] |
delitem(obj, k) |
Indexing | obj[k] |
getitem(obj, k) |
Left Shift | a << b |
lshift(a, b) |
Modulo | a % b |
mod(a, b) |
Multiplication | a * b |
mul(a, b) |
Matrix Multiplication | a @ b |
matmul(a, b) |
Negation (Arithmetic) | - a |
neg(a) |
Negation (Logical) | not a |
not_(a) |
Positive | + a |
pos(a) |
Right Shift | a >> b |
rshift(a, b) |
Slice Assignment | seq[i:j] = values |
setitem(seq, slice(i, j), values) |
Slice Deletion | del seq[i:j] |
delitem(seq, slice(i, j)) |
Slicing | seq[i:j] |
getitem(seq, slice(i, j)) |
String Formatting | s % obj |
mod(s, obj) |
Subtraction | a - b |
sub(a, b) |
Truth Test | obj |
truth(obj) |
Ordering | a < b |
lt(a, b) |
Ordering | a <= b |
le(a, b) |
Equality | a == b |
eq(a, b) |
Difference | a != b |
ne(a, b) |
Ordering | a >= b |
ge(a, b) |
Ordering | a > b |
gt(a, b) |