operator
— Standard operators as functions标准运算符作为函数¶
Source code: Lib/operator.py
The operator
module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y)
is equivalent to the expression x+y
. operator
模块导出一组与Python的内部运算符相对应的有效函数。例如,运算符operator.add(x, y)
等价于表达式x+y
。Many function names are those used for special methods, without the double underscores. 许多函数名用于特殊方法,没有双下划线。For backward compatibility, many of these have a variant with the double underscores kept. 为了向后兼容,其中许多具有保留双下划线的变体。The variants without the double underscores are preferred for clarity.为清晰起见,首选不带双下划线的变体。
The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations.这些函数分为执行对象比较、逻辑运算、数学运算和序列运算的类别。
The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:对象比较函数对所有对象都很有用,并以其支持的丰富比较运算符命名:
-
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)¶ Perform “rich comparisons” between a and b.在a和b之间进行“丰富的比较”。Specifically,具体来说,lt(a, b)
is equivalent toa < b
,le(a, b)
is equivalent toa <= b
,eq(a, b)
is equivalent toa == b
,ne(a, b)
is equivalent toa != b
,gt(a, b)
is equivalent toa > b
andge(a, b)
is equivalent toa >= b
.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
。Note that these functions can return any value, which may or may not be interpretable as a Boolean value.请注意,这些函数可以返回任何值,这些值可以解释为布尔值,也可以不解释为布尔值。See Comparisons for more information about rich comparisons.有关丰富比较的更多信息,请参阅比较。
The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations:逻辑运算通常也适用于所有对象,并支持真值测试、身份测试和布尔运算:
-
operator.
not_
(obj)¶ -
operator.
__not__
(obj)¶ Return the outcome of返回not
obj.not
obj的结果。(Note that there is no(注意,对象实例没有__not__()
method for object instances; only the interpreter core defines this operation.__not__()
方法;只有解释器核心定义此操作。The result is affected by the结果受__bool__()
and__len__()
methods.)__bool__()
和__len__()
方法的影响。)
-
operator.
truth
(obj)¶ Return如果obj为True
if obj is true, andFalse
otherwise.True
,则返回True
,否则返回False
。This is equivalent to using the这相当于使用bool
constructor.bool
构造函数。
-
operator.
is_
(a, b)¶ Return返回a is b
.a is b
。Tests object identity.测试对象标识。
-
operator.
is_not
(a, b)¶ Return返回a is not b
.a is not b
。Tests object identity.测试对象标识。
The mathematical and bitwise operations are the most numerous:数学运算和位运算最多:
-
operator.
index
(a)¶ -
operator.
__index__
(a)¶ Return a converted to an integer.返回a转换为整数。Equivalent to相当于a.__index__()
.a.__index__()
。
-
operator.
inv
(obj)¶ -
operator.
invert
(obj)¶ -
operator.
__inv__
(obj)¶ -
operator.
__invert__
(obj)¶ Return the bitwise inverse of the number obj.返回数字obj的位逆。This is equivalent to这相当于~obj
.~obj
。
-
operator.
truediv
(a, b)¶ -
operator.
__truediv__
(a, b)¶ Return返回a / b
where 2/3 is .66 rather than 0.a/b
,其中2/3为.66而不是0。This is also known as “true” division.这也称为“真实”分割。
Operations which work with sequences (some of them with mappings too) include:处理序列的操作(其中一些也处理映射)包括:
-
operator.
contains
(a, b)¶ -
operator.
__contains__
(a, b)¶ Return the outcome of the test返回b in a
.b in a
测试的结果。Note the reversed operands.请注意反转的操作数。
-
operator.
countOf
(a, b)¶ Return the number of occurrences of b in a.返回a中b的出现次数。
-
operator.
indexOf
(a, b)¶ Return the index of the first of occurrence of b in a.返回a中b第一次出现的索引。
-
operator.
setitem
(a, b, c)¶ -
operator.
__setitem__
(a, b, c)¶ Set the value of a at index b to c.将索引b处的a值设置为c。
-
operator.
length_hint
(obj, default=0)¶ Return an estimated length for the object o.返回对象o的估计长度。First try to return its actual length, then an estimate using首先尝试返回其实际长度,然后使用object.__length_hint__()
, and finally return the default value.object.__length_hint__()
进行估计,最后返回默认值。New in version 3.4.版本3.4中新增。
The operator
module also defines tools for generalized attribute and item lookups. operator
模块还定义了用于通用属性和项查找的工具。These are useful for making fast field extractors as arguments for 这些对于将快速字段提取器作为map()
, sorted()
, itertools.groupby()
, or other functions that expect a function argument.map()
、sorted()
、itertools.groupby()
或其他需要函数参数的函数的参数非常有用。
-
operator.
attrgetter
(attr)¶ -
operator.
attrgetter
(*attrs) Return a callable object that fetches attr from its operand.返回一个可调用对象,该对象从其操作数中获取attr。If more than one attribute is requested, returns a tuple of attributes.如果请求了多个属性,则返回属性元组。The attribute names can also contain dots.属性名称也可以包含点。For example:例如:After在f = attrgetter('name')
, the callf(b)
returnsb.name
.f = attrgetter('name')
之后,调用f(b)
返回b.name
。After在f = attrgetter('name', 'date')
, the callf(b)
returns(b.name, b.date)
.f = attrgetter('name', 'date')
之后,调用f(b)
返回(b.name, b.date)
。After在f = attrgetter('name.first', 'name.last')
, the callf(b)
returns(b.name.first, b.name.last)
.f = attrgetter('name.first', 'name.last')
之后,调用f(b)
返回(b.name.first, b.name.last)
。
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
-
operator.
itemgetter
(item)¶ -
operator.
itemgetter
(*items) Return a callable object that fetches item from its operand using the operand’s返回一个可调用的对象,该对象使用操作数的__getitem__()
method.__getitem__()
方法从其操作数中获取item。If multiple items are specified, returns a tuple of lookup values.如果指定了多个项,则返回查找值的元组。For example:例如:After在f = itemgetter(2)
, the callf(r)
returnsr[2]
.f = itemgetter(2)
之后,调用f(r)
返回r[2]
。After在g = itemgetter(2, 5, 3)
, the callg(r)
returns(r[2], r[5], r[3])
.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 gThe items can be any type accepted by the operand’s这些项可以是操作数的__getitem__()
method.__getitem__()
方法接受的任何类型。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'Example of using使用itemgetter()
to retrieve specific fields from a tuple record:itemgetter()
从元组记录中检索特定字段的示例:>>> 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)¶ Return a callable object that calls the method name on its operand.返回一个可调用对象,该对象调用其操作数上的方法name。If additional arguments and/or keyword arguments are given, they will be given to the method as well.如果提供了其他参数和/或关键字参数,则它们也将提供给该方法。For example:例如:After在f = methodcaller('name')
, the callf(b)
returnsb.name()
.f = methodcaller('name')
之后,调用f(b)
返回b.name()
。After在f = methodcaller('name', 'foo', bar=1)
, the callf(b)
returnsb.name('foo', bar=1)
.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
Mapping Operators to Functions将运算符映射到函数¶
This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the 此表显示了抽象操作如何对应Python语法中的运算符符号和operator
module.operator
模块中的函数。
|
|
|
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
In-place Operators就地运算符¶
Many operations have an “in-place” version. Listed below are functions providing a more primitive access to in-place operators than the usual syntax does; for example, the statement 许多操作都有“就地”版本。下面列出的函数提供了比通常语法更原始的就地运算符访问;例如,语句x += y
is equivalent to x = operator.iadd(x, y)
. x += y
相当于x = operator.iadd(x, y)
。Another way to put it is to say that 另一种说法是,z = operator.iadd(x, y)
is equivalent to the compound statement z = x; z += y
.z = operator.iadd(x, y)
等价于复合语句z = x; z += y
。
In those examples, note that when an in-place method is called, the computation and assignment are performed in two separate steps. 在这些示例中,请注意,当调用就地方法时,计算和赋值分两个单独的步骤执行。The in-place functions listed below only do the first step, calling the in-place method. 下面列出的就地函数只执行第一步,即调用就地方法。The second step, assignment, is not handled.第二步,分配,没有处理。
For immutable targets such as strings, numbers, and tuples, the updated value is computed, but not assigned back to the input variable:对于字符串、数字和元组等不可变目标,会计算更新后的值,但不会将其分配回输入变量:
>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
>>> a
'hello'
For mutable targets such as lists and dictionaries, the in-place method will perform the update, so no subsequent assignment is necessary:对于列表和字典等可变目标,就地方法将执行更新,因此无需后续赋值:
>>> 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']
-
operator.
iconcat
(a, b)¶ -
operator.
__iconcat__
(a, b)¶ a = iconcat(a, b)
is equivalent to对于a和b序列,等价于a += b
for a and b sequences.a += b
。
-
operator.
ifloordiv
(a, b)¶ -
operator.
__ifloordiv__
(a, b)¶ a = ifloordiv(a, b)
is equivalent to等于a //= b
.a//=b
。
-
operator.
ilshift
(a, b)¶ -
operator.
__ilshift__
(a, b)¶ a = ilshift(a, b)
is equivalent to等于a <<= b
.a <<= b
。
-
operator.
imatmul
(a, b)¶ -
operator.
__imatmul__
(a, b)¶ a = imatmul(a, b)
is equivalent to等于a @= b
.@=b
。New in version 3.5.版本3.5中新增。
-
operator.
irshift
(a, b)¶ -
operator.
__irshift__
(a, b)¶ a = irshift(a, b)
is equivalent to等于a >>= b
.a>>=b
。