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

源代码: Lib/operator.py


operator模块导出一组与 Python 的固有运算符相对应的有效函数。例如,operator.add(x, y)等效于表达式x+y。许多函数名称是用于特殊方法的名称,没有双下划线。为了向后兼容,其中许多具有保留双下划线的变体。为了清楚起见,不带双下划线的变体是首选。

这些函数分为执行对象比较,逻辑运算,math 运算和序列运算的类别。

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

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

math 和按位运算是最多的:

3.5 版中的新Function。

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

3.4 版的新Function。

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

Equivalent to:

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

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('name')({'name': 'tu', 'age': 18})
'tu'
>>> 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'

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

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

Equivalent to:

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

将运算符 Map 到函数

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

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)
按位异或 a ^ b xor(a, b)
Bitwise Inversion ~ a invert(a)
Bitwise Or a | b 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)

In-place Operators

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

在这些示例中,请注意,当调用就地方法时,计算和分配是在两个单独的步骤中执行的。下面列出的就地函数仅执行第一步,即调用就地方法。第二步,分配,不处理。

对于不可变的目标(例如字符串,数字和 Tuples),将计算更新后的值,但不会将其分配回 Importing 变量:

>>> a = 'hello'
>>> iadd(a, ' world')
'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']

3.5 版中的新Function。

首页