9.9. 运算符-标准运算符作为函数

operator模块导出一组与 Python 的固有运算符相对应的有效函数。例如,operator.add(x, y)等效于表达式x+y。函数名称是用于特殊类方法的名称。为方便起见,还提供了没有前导和尾随__的变体。

这些函数属于执行对象比较,逻辑运算,math 运算,序列运算和抽象类型测试的类别。

对象比较Function对所有对象都有用,并以它们支持的丰富比较运算符命名:

  • 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 *)
    • 在* a b *之间执行“丰富比较”。具体而言,lt(a, b)等效于a < ble(a, b)等效于a <= beq(a, b)等效于a == bne(a, b)等效于a != bgt(a, b)等效于a > bge(a, b)等效于a >= b。请注意,与内置的cmp()不同,这些函数可以返回任何值,该值可以或可以不解释为布尔值。有关丰富比较的更多信息,请参见Comparisons

2.2 版中的新Function。

逻辑运算通常也适用于所有对象,并支持真值测试,身份测试和布尔运算:

  • operator. not_(* obj *)

  • operator. __not__(* obj *)

    • 返回not * obj *的结果。 (请注意,对象实例没有not()方法;只有解释器内核定义了此操作。结果受nonzero()len()方法的影响。)
  • operator. truth(* obj *)

    • 如果 obj *为 true,则返回True,否则返回False。这等效于使用bool构造函数。
  • operator. is_(* a b *)

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

2.3 版的新Function。

  • operator. is_not(* a b *)
    • 返回a is not b。测试对象身份。

2.3 版的新Function。

math 和按位运算是最多的:

  • operator. abs(* obj *)

  • operator. __abs__(* obj *)

    • 返回* obj *的绝对值。
  • operator. add(* a b *)

  • operator. __add__(* a b *)

    • 返回a + b,以获得* a b *数字。
  • operator. and_(* a b *)

  • operator. __and__(* a b *)

    • 返回* a b *的按位与。
  • operator. div(* a b *)

  • operator. __div__(* a b *)

    • __future__.division无效时返回a / b。这也称为“经典”划分。
  • operator. floordiv(* a b *)

  • operator. __floordiv__(* a b *)

    • 返回a // b

2.2 版中的新Function。

  • operator. index(* a *)
  • operator. __index__(* a *)
    • 返回* a *转换为整数。等效于a.__index__()

2.5 版的新Function。

  • operator. inv(* obj *)
  • operator. invert(* obj *)
  • operator. __inv__(* obj *)
  • operator. __invert__(* obj *)
    • 返回数字* obj *的按位倒数。这等效于~obj

2.0 版的新Function:名称invert()invert()

  • operator. lshift(* a b *)

  • operator. __lshift__(* a b *)

    • 返回* a 向左移动 b *。
  • operator. mod(* a b *)

  • operator. __mod__(* a b *)

    • 返回a % b
  • operator. mul(* a b *)

  • operator. __mul__(* a b *)

    • 返回a * b,以获得* a b *数字。
  • operator. neg(* obj *)

  • operator. __neg__(* obj *)

    • 返回* obj *否定(-obj)。
  • operator. or_(* a b *)

  • operator. __or__(* a b *)

    • 返回* a b *的按位或。
  • operator. pos(* obj *)

  • operator. __pos__(* obj *)

    • 返回* obj *正(+obj)。
  • operator. pow(* a b *)

  • operator. __pow__(* a b *)

    • 返回a ** b,以获得* a b *数字。

2.3 版的新Function。

  • operator. rshift(* a b *)

  • operator. __rshift__(* a b *)

    • 返回* a 向右移动 b *。
  • operator. sub(* a b *)

  • operator. __sub__(* a b *)

    • 返回a - b
  • operator. truediv(* a b *)

  • operator. __truediv__(* a b *)

    • __future__.division有效时返回a / b。这也称为“真实”划分。

2.2 版中的新Function。

  • operator. xor(* a b *)
  • operator. __xor__(* a b *)
    • 返回* a b *的按位异或。

适用于序列的操作(其中一些也适用于 Map)包括:

  • operator. concat(* a b *)

  • operator. __concat__(* a b *)

    • 为** a b *序列返回a + b
  • operator. contains(* a b *)

  • operator. __contains__(* a b *)

    • 返回测试结果b in a。注意相反的操作数。

2.0 版的新Function:名称contains()

  • operator. countOf(* a b *)

    • 返回* a b *的出现次数。
  • operator. delitem(* a b *)

  • operator. __delitem__(* a b *)

    • 删除索引* b 处的 a *值。
  • operator. delslice(* a b c *)

  • operator. __delslice__(* a b c *)

    • 从索引* b 删除 a 的切片到索引 c-1 *。

自 2.6 版起不推荐使用:此Function在 Python 3.x 中已删除。将delitem()与切片索引一起使用。

  • operator. getitem(* a b *)

  • operator. __getitem__(* a b *)

    • 在索引* b 处返回 a *的值。
  • operator. getslice(* a b c *)

  • operator. __getslice__(* a b c *)

    • 将* a 的片段从索引 b 返回到索引 c-1 *。

自 2.6 版起不推荐使用:此Function在 Python 3.x 中已删除。将getitem()与切片索引一起使用。

  • operator. indexOf(* a b *)

    • 返回* a 中第一次出现 b *的索引。
  • operator. repeat(* a b *)

  • operator. __repeat__(* a b *)

    • 从 2.7 版开始不推荐使用:改为使用mul()

返回a * b,其中* a 是一个序列, b *是一个整数。

  • operator. sequenceIncludes ( ... )
    • 自 2.0 版起弃用:改为使用contains()

contains()的别名。

  • operator. setitem(* a b c *)

  • operator. __setitem__(* a b c *)

    • 将索引* b 处的 a 值设置为 c *。
  • operator. setslice(* a b c v *)

  • operator. __setslice__(* a b c v *)

    • 将从索引* b 到索引 c-1 a 切片设置为序列 v *。

自 2.6 版起不推荐使用:此Function在 Python 3.x 中已删除。将setitem()与切片索引一起使用。

使用运算符Function的示例:

>>> # Elementwise multiplication
>>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
[0, 20, 60, 120]

>>> # Dot product
>>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
200

许多操作都有“就地”版本。与通常的语法相比,以下函数提供了对原位运算符的更原始的访问;例如statement x += y等效于x = operator.iadd(x, y)。换句话说,z = operator.iadd(x, y)等效于复合语句z = x; z += y

  • operator. iadd(* a b *)
  • operator. __iadd__(* a b *)
    • a = iadd(a, b)等效于a += b

2.5 版的新Function。

  • operator. iand(* a b *)
  • operator. __iand__(* a b *)
    • a = iand(a, b)等效于a &= b

2.5 版的新Function。

  • operator. iconcat(* a b *)
  • operator. __iconcat__(* a b *)
    • 对于* a b *序列,a = iconcat(a, b)等效于a += b

2.5 版的新Function。

  • operator. idiv(* a b *)
  • operator. __idiv__(* a b *)
    • __future__.division无效时,a = idiv(a, b)等效于a /= b

2.5 版的新Function。

  • operator. ifloordiv(* a b *)
  • operator. __ifloordiv__(* a b *)
    • a = ifloordiv(a, b)等效于a //= b

2.5 版的新Function。

  • operator. ilshift(* a b *)
  • operator. __ilshift__(* a b *)
    • a = ilshift(a, b)等效于a <<= b

2.5 版的新Function。

  • operator. imod(* a b *)
  • operator. __imod__(* a b *)
    • a = imod(a, b)等效于a %= b

2.5 版的新Function。

  • operator. imul(* a b *)
  • operator. __imul__(* a b *)
    • a = imul(a, b)等效于a *= b

2.5 版的新Function。

  • operator. ior(* a b *)
  • operator. __ior__(* a b *)
    • a = ior(a, b)等效于a |= b

2.5 版的新Function。

  • operator. ipow(* a b *)
  • operator. __ipow__(* a b *)
    • a = ipow(a, b)等效于a **= b

2.5 版的新Function。

  • operator. irepeat(* a b *)
  • operator. __irepeat__(* a b *)
    • 从 2.7 版开始不推荐使用:改为使用imul()

a = irepeat(a, b)等效于a *= b,其中* a 是一个序列, b *是一个整数。

2.5 版的新Function。

  • operator. irshift(* a b *)
  • operator. __irshift__(* a b *)
    • a = irshift(a, b)等效于a >>= b

2.5 版的新Function。

  • operator. isub(* a b *)
  • operator. __isub__(* a b *)
    • a = isub(a, b)等效于a -= b

2.5 版的新Function。

  • operator. itruediv(* a b *)
  • operator. __itruediv__(* a b *)
    • __future__.division有效时,a = itruediv(a, b)等效于a /= b

2.5 版的新Function。

  • operator. ixor(* a b *)
  • operator. __ixor__(* a b *)
    • a = ixor(a, b)等效于a ^= b

2.5 版的新Function。

operator模块还定义了一些谓词来测试对象的类型。但是,这些都不都是可靠的。最好改为测试抽象 Base Class(有关详细信息,请参见collectionsnumbers)。

  • operator. isCallable(* obj *)
    • 自 2.0 版起弃用:改为使用isinstance(x, collections.Callable)

如果对象* obj *可以像函数一样调用,则返回 true;否则返回 false。对于支持call()方法的函数,绑定和未绑定方法,类对象和实例对象,返回 True。

  • operator. isMappingType(* obj *)
    • 从 2.7 版开始不推荐使用:改为使用isinstance(x, collections.Mapping)

如果对象* obj *支持 Map 接口,则返回 true。这对于字典和所有定义getitem()的实例对象都是如此。

  • operator. isNumberType(* obj *)
    • 从 2.7 版开始不推荐使用:改为使用isinstance(x, numbers.Number)

如果对象* obj *表示数字,则返回 true。对于用 C 实现的所有数字类型都是如此。

  • operator. isSequenceType(* obj *)
    • 从 2.7 版开始不推荐使用:改为使用isinstance(x, collections.Sequence)

如果对象* obj *支持序列协议,则返回 true。对于在 C 中定义序列方法的所有对象以及定义getitem()的所有实例对象,此方法返回 true。

operator模块还定义了用于通用属性和项目查找的工具。这些对于将快速字段提取器用作map()sorted()itertools.groupby()或需要函数参数的其他函数的参数很有用。

  • operator. attrgetter(* attr *)

  • operator. attrgetter(“ **” *)

    • 返回从其操作数获取* attr *的可调用对象。如果请求多个属性,则返回一个 Tuples。属性名称也可以包含点。例如:
  • 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)

Equivalent to:

def attrgetter(*items):
    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

2.4 版的新Function。

在版本 2.5 中进行了更改:添加了对多个属性的支持。

在 2.6 版中进行了更改:添加了对点属性的支持。

  • operator. itemgetter(* item *)

  • operator. itemgetter(*)

    • 返回使用操作数的getitem()方法从其操作数中获取* item *的可调用对象。如果指定了多个项目,则返回查找值的 Tuples。例如:
  • f = itemgetter(2)之后,呼叫f(r)返回r[2]

  • g = itemgetter(2, 5, 3)之后,呼叫g(r)返回(r[2], r[5], r[3])

Equivalent to:

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

这些项目可以是操作数的getitem()方法接受的任何类型。字典接受任何可哈希值。列表,Tuples 和字符串接受索引或切片:

>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG'

2.4 版的新Function。

在版本 2.5 中进行了更改:添加了对多项目提取的支持。

使用itemgetter()从 TuplesLogging 检索特定字段的示例:

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

    • 返回一个可调用对象,该对象在其操作数上调用方法* name *。如果给出了其他参数和/或关键字参数,它们也将被赋予方法。例如:
  • f = methodcaller('name')之后,呼叫f(b)返回b.name()

  • f = methodcaller('name', 'foo', bar=1)之后,呼叫f(b)返回b.name('foo', bar=1)

Equivalent to:

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

2.6 版的新Function。

9.9.1. 将运算符 Map 到函数

下表显示了抽象运算如何与 Python 语法中的运算符和operator模块中的函数相对应。

OperationSyntaxFunction
Additiona + badd(a, b)
Concatenationseq1 + seq2concat(seq1, seq2)
Containment Testobj in seqcontains(seq, obj)
Divisiona / bdiv(a, b)(无__future__.division)
Divisiona / btruediv(a, b)(使用__future__.division)
Divisiona // bfloordiv(a, b)
Bitwise Anda & band_(a, b)
按位异或a ^ bxor(a, b)
Bitwise Inversion~ ainvert(a)
Bitwise Ora | bor_(a, b)
Exponentiationa ** bpow(a, b)
Identitya is bis_(a, b)
Identitya is not bis_not(a, b)
Indexed Assignmentobj[k] = vsetitem(obj, k, v)
Indexed Deletiondel obj[k]delitem(obj, k)
Indexingobj[k]getitem(obj, k)
Left Shifta << blshift(a, b)
Moduloa % bmod(a, b)
Multiplicationa * bmul(a, b)
Negation (Arithmetic)- aneg(a)
Negation (Logical)not anot_(a)
Positive+ apos(a)
Right Shifta >> brshift(a, b)
Sequence Repetitionseq * irepeat(seq, i)
Slice Assignmentseq[i:j] = valuessetitem(seq, slice(i, j), values)
Slice Deletiondel seq[i:j]delitem(seq, slice(i, j))
Slicingseq[i:j]getitem(seq, slice(i, j))
String Formattings % objmod(s, obj)
Subtractiona - bsub(a, b)
Truth Testobjtruth(obj)
Orderinga < blt(a, b)
Orderinga <= ble(a, b)
Equalitya == beq(a, b)
Differencea != bne(a, b)
Orderinga >= bge(a, b)
Orderinga > bgt(a, b)