Source code: Lib/operator.py

ooperator módulo exporta um conjunto de funções eficientes correspondentes aos operadores intrínsecos do Python. Por exemplo, operator.add(x, y) isequivalente à expressãox+y. Muitos nomes de funções são aqueles usados para métodos especiais, sem o duplo underscores. Para compatibilidade reversa, muitos deles têm uma variante com os underscores duplos mantidos., As variantesque não têm os duplos pontos de referência são preferidaspara maior clareza.

as funções caem em categorias que realizam comparações de objetos, operações logicais, operações matemáticas e operações sequenciais., id=”84ef065d38″>__ne__(a, b)¶ operator.__ge__(a, b)¶ operator.__gt__(a, b)¶

The logical operations are also generally applicable to all objects, and supporttruth tests, identity tests, and boolean operations:

operator.not_(obj)¶operator.__not__(obj)¶operator.truth(obj)¶

Return True if obj is true, and False otherwise., This isequivalent to using the bool constructor.

operator.is_(a, b)¶

Return a is b. Tests object identity.

operator.is_not(a, b)¶

Return a is not b. Tests object identity.

The mathematical and bitwise operations are the most numerous:

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

Return the absolute value of obj.,

operator.add(a, b)¶operator.__add__(a, b)¶

Return a + b, for a and b numbers.

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

Return the bitwise and of a and b.

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

Return a // b.,

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

Return a converted to an integer. Equivalent to a.__index__().

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

Return the bitwise inverse of the number obj. This is equivalent to ~obj.,

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

Return a shifted left by b.

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

Return a % b.

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

Return a * b, for a and b numbers.,

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

Return a @ b.

New in version 3.5.

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

Return obj negated (-obj).

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

Return the bitwise or of a and b.,

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

Return obj positive (+obj).

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

Return a ** b, for a and b numbers.

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

Return a shifted right by b.,

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

Return a - b.

operator.truediv

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

Return a / b where 2/3 is .66 rather than 0. This is also known as”true” division.

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

Return the bitwise exclusive or of a and b.,

as Operações que o trabalho com sequências (alguns deles com mapeamentos também) incluem:

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

Voltar a + b para a e b seqüências.

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

Retornar o resultado do teste b in a. Reparem nos operandos invertidos.,

operator.countOf(a, b) n

Retornar o número de ocorrências de b em a.

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

Remover o valor de a em b de índice.

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

Retornar o valor de um índice b.

operator.indexOf(a, b) n

Retornar o índice da primeira ocorrência de b em um.,

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

Definir o valor de um índice b para c.

operator.length_hint(obj, padrão=0)¶

Retornar um comprimento estimado para o objeto. Primeiro tentar voltar itsactual de comprimento, então uma estimativa usando object.__length_hint__(), andfinally retornar o valor padrão.

novo na versão 3.4.

Theoperator module also defines tools for generalized attribute and itemlookups., Estes são úteis para a tomada rápida de campo extratores como argumentos paramap() sorted() itertools.groupby(), ou outras funções thatexpect um argumento de função.

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

Retornar uma chamada de objeto que busca attr de seu operando.Se for pedido mais do que um atributo, devolve uma tupla de atributos.Os nomes dos atributos também podem conter pontos., Por exemplo:

Equivalente a:

operator.itemgetter(item)¶operator.itemgetter(*itens)

Retornar uma chamada de objeto que busca item do seu operando usando theoperand do __getitem__() método. Se forem indicados vários itens, devolve uma tupla de valores de pesquisa. Por exemplo:

  • Depois f = itemgetter(2), a chamada f(r) retorna r.,

  • Depois g = itemgetter(2, 5, 3), a chamada g(r) retorna(r, r, r).

Equivalent to:

The items can be any type accepted by the operand’s__getitem__()method. Os dicionários aceitam qualquer valor hashable., Listas, tuplas, andstrings aceitar um índice ou uma fatia:

>>> soldier = dict(rank='captain', name='dotterbart')>>> itemgetter('rank')(soldier)'captain'

Exemplo de uso itemgetter() para recuperar campos específicos de atuple registo:

operator.methodcaller(nome, /, *args, **kwargs) n

de Retorno de uma chamada de objeto que chama o nome do método em seu operando. Argumentos ifadicional e / ou argumentos de palavra-chave são dados, eles serão dados o método também. Por exemplo:

  • Depois f = methodcaller('name'), a chamada f(b) retorna b.name().,

  • After f = methodcaller('name', 'foo', bar=1), the call f(b)returns b.name('foo', bar=1).

Equivalent to:

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

Deixe uma resposta

O seu endereço de email não será publicado. Campos obrigatórios marcados com *