# `operator` --- 标准运算符替代函数¶

`operator` 模块提供了一套与Python的内置运算符对应的高效率函数。例如，`operator.add(x, y)` 与表达式 `x+y` 相同。 许多函数名与特殊方法名相同，只是没有双下划线。为了向后兼容性，也保留了许多包含双下划线的函数。为了表述清楚，建议使用没有双下划线的函数。

operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)

ab 之间进行全比较。具体的，`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` 相同，`ge(a, b)``与 ``a >= b` 相同。注意这些函数可以返回任何值，无论它是否可当作布尔值。关于全比较的更多信息请参考 比较运算

operator.not_(obj)
operator.__not__(obj)

operator.truth(obj)

operator.is_(a, b)

operator.is_not(a, b)

operator.abs(obj)
operator.__abs__(obj)

operator.and_(a, b)
operator.__and__(a, b)

operator.floordiv(a, b)
operator.__floordiv__(a, b)

operator.index(a)
operator.__index__(a)

operator.inv(obj)
operator.invert(obj)
operator.__inv__(obj)
operator.__invert__(obj)

operator.lshift(a, b)
operator.__lshift__(a, b)

operator.mod(a, b)
operator.__mod__(a, b)

operator.mul(a, b)
operator.__mul__(a, b)

operator.matmul(a, b)
operator.__matmul__(a, b)

3.5 新版功能.

operator.neg(obj)
operator.__neg__(obj)

operator.or_(a, b)
operator.__or__(a, b)

operator.pos(obj)
operator.__pos__(obj)

operator.pow(a, b)
operator.__pow__(a, b)

operator.rshift(a, b)
operator.__rshift__(a, b)

operator.sub(a, b)
operator.__sub__(a, b)

operator.truediv(a, b)
operator.__truediv__(a, b)

operator.xor(a, b)
operator.__xor__(a, b)

operator.concat(a, b)
operator.__concat__(a, b)

operator.contains(a, b)
operator.__contains__(a, b)

operator.countOf(a, b)

operator.delitem(a, b)
operator.__delitem__(a, b)

operator.getitem(a, b)
operator.__getitem__(a, b)

operator.indexOf(a, b)

operator.setitem(a, b, c)
operator.__setitem__(a, b, c)

a 中索引号为 b 的值设为 c

operator.length_hint(obj, default=0)

Return an estimated length for the object obj. First try to return its actual length, then an estimate using `object.__length_hint__()`, and finally return the default value.

3.4 新版功能.

The following operation works with callables:

operator.call(obj, /, *args, **kwargs)
operator.__call__(obj, /, *args, **kwargs)

Return `obj(*args, **kwargs)`.

3.11 新版功能.

`operator` 模块还定义了一些用于常规属性和条目查找的工具。 这些工具适合用来编写快速字段提取器作为 `map()`, `sorted()`, `itertools.groupby()` 或其他需要相应函数参数的函数的参数。

operator.attrgetter(attr)
operator.attrgetter(*attrs)

• `f = attrgetter('name')` 之后，调用 `f(b)` 将返回 `b.name`

• `f = attrgetter('name', 'date')` 之后，调用 `f(b)` 将返回 `(b.name, b.date)`

• `f = attrgetter('name.first', 'name.last')` 之后，调用 `f(b)` 将返回 `(b.name.first, b.name.last)`

```def attrgetter(*items):
if any(not isinstance(item, str) for item in items):
raise TypeError('attribute name must be a string')
if len(items) == 1:
attr = items[0]
def g(obj):
return resolve_attr(obj, attr)
else:
def g(obj):
return tuple(resolve_attr(obj, attr) for attr in items)
return g

def resolve_attr(obj, attr):
for name in attr.split("."):
obj = getattr(obj, name)
return obj
```
operator.itemgetter(item)
operator.itemgetter(*items)

• `f = itemgetter(2)` 之后，调用 `f(r)` 将返回 `r[2]`

• `g = itemgetter(2, 5, 3)` 之后，调用 `g(r)` 将返回 `(r[2], r[5], r[3])`

```def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
```

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:

```>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1, 3, 5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2, None))('ABCDEFG')
'CDEFG'
>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'
```

```>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> list(map(getcount, inventory))
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
```
operator.methodcaller(name, /, *args, **kwargs)

• `f = methodcaller('name')` 之后，调用 `f(b)` 将返回 `b.name()`

• `f = methodcaller('name', 'foo', bar=1)` 之后，调用 `f(b)` 将返回 `b.name('foo', bar=1)`

```def methodcaller(name, /, *args, **kwargs):
def caller(obj):
return getattr(obj, name)(*args, **kwargs)
return caller
```

## 将运算符映射到函数¶

`a + b`

`add(a, b)`

`seq1 + seq2`

`concat(seq1, seq2)`

`obj in seq`

`contains(seq, obj)`

`a / b`

`truediv(a, b)`

`a // b`

`floordiv(a, b)`

`a & b`

`and_(a, b)`

`a ^ b`

`xor(a, b)`

`~ a`

`invert(a)`

`a | b`

`or_(a, b)`

`a ** b`

`pow(a, b)`

`a is b`

`is_(a, b)`

`a is not b`

`is_not(a, b)`

`obj[k] = v`

`setitem(obj, k, v)`

`del obj[k]`

`delitem(obj, k)`

`obj[k]`

`getitem(obj, k)`

`a << b`

`lshift(a, b)`

`a % b`

`mod(a, b)`

`a * b`

`mul(a, b)`

`a @ b`

`matmul(a, b)`

`- a`

`neg(a)`

`not a`

`not_(a)`

`+ a`

`pos(a)`

`a >> b`

`rshift(a, b)`

`seq[i:j] = values`

`setitem(seq, slice(i, j), values)`

`del seq[i:j]`

`delitem(seq, slice(i, j))`

`seq[i:j]`

`getitem(seq, slice(i, j))`

`s % obj`

`mod(s, obj)`

`a - b`

`sub(a, b)`

`obj`

`truth(obj)`

`a < b`

`lt(a, b)`

`a <= b`

`le(a, b)`

`a == b`

`eq(a, b)`

`a != b`

`ne(a, b)`

`a >= b`

`ge(a, b)`

`a > b`

`gt(a, b)`

## 原地运算符¶

```>>> a = 'hello'
'hello world'
>>> a
'hello'
```

```>>> s = ['h', 'e', 'l', 'l', 'o']
>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> s
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
```

`a = iadd(a, b)` 等价于 `a += b`

operator.iand(a, b)
operator.__iand__(a, b)

`a = iand(a, b)` 等价于 `a &= b`

operator.iconcat(a, b)
operator.__iconcat__(a, b)

`a = iconcat(a, b)` 等价于 `a += b` 其中 ab 为序列。

operator.ifloordiv(a, b)
operator.__ifloordiv__(a, b)

`a = ifloordiv(a, b)` 等价于 `a //= b`

operator.ilshift(a, b)
operator.__ilshift__(a, b)

`a = ilshift(a, b)` 等价于 `a <<= b`

operator.imod(a, b)
operator.__imod__(a, b)

`a = imod(a, b)` 等价于 `a %= b`

operator.imul(a, b)
operator.__imul__(a, b)

`a = imul(a, b)` 等价于 `a *= b`

operator.imatmul(a, b)
operator.__imatmul__(a, b)

`a = imatmul(a, b)` 等价于 `a @= b`

3.5 新版功能.

operator.ior(a, b)
operator.__ior__(a, b)

`a = ior(a, b)` 等价于 `a |= b`

operator.ipow(a, b)
operator.__ipow__(a, b)

`a = ipow(a, b)` 等价于 `a **= b`

operator.irshift(a, b)
operator.__irshift__(a, b)

`a = irshift(a, b)` 等价于 `a >>= b`

operator.isub(a, b)
operator.__isub__(a, b)

`a = isub(a, b)` 等价于 `a -= b`

operator.itruediv(a, b)
operator.__itruediv__(a, b)

`a = itruediv(a, b)` 等价于 `a /= b`

operator.ixor(a, b)
operator.__ixor__(a, b)

`a = ixor(a, b)` 等价于 `a ^= b`