# `operator` --- 標準運算子替代函式¶

`operator` module（模組）提供了一套與 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 之間進行 "rich comparison"。具體來說，`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` 相同。注意這些函式可以回傳任何值，無論它是否可當作 boolean（布林）值。關於 rich comparison 的更多資訊請參考 比较运算

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)

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)

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

`operator` module 還定義了一些用於常規屬性和條目查詢的工具。這些工具適合用來編寫快速欄位提取器以作為 `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
```

```>>> 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)`

## 原地 (in-place) 運算子¶

```>>> 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`

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`