Movatterモバイル変換


[0]ホーム

URL:


Navigation

operator — Standard operators as functions

Theoperator module exports a set of functions implemented in Ccorresponding to the intrinsic operators of Python. For example,operator.add(x,y) is equivalent to the expressionx+y. The functionnames are those used for special class methods; variants without leading andtrailing__ are also provided for convenience.

The functions fall into categories that perform object comparisons, logicaloperations, mathematical operations, sequence operations, and abstract typetests.

The object comparison functions are useful for all objects, and are named afterthe 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” betweena andb. Specifically,lt(a,b) isequivalent 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. Note that unlike the built-incmp(), these functions canreturn any value, which may or may not be interpretable as a Boolean value.SeeComparisons for more information about rich comparisons.

New in version 2.2.

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

operator.not_(obj)
operator.__not__(obj)
Return the outcome ofnotobj. (Note that there is no__not__() method for object instances; only the interpreter core definesthis operation. The result is affected by the__nonzero__() and__len__() methods.)
operator.truth(obj)
ReturnTrue ifobj is true, andFalse otherwise. This isequivalent to using thebool constructor.
operator.is_(a,b)

Returnaisb. Tests object identity.

New in version 2.3.

operator.is_not(a,b)

Returnaisnotb. Tests object identity.

New in version 2.3.

The mathematical and bitwise operations are the most numerous:

operator.abs(obj)
operator.__abs__(obj)
Return the absolute value ofobj.
operator.add(a,b)
operator.__add__(a,b)
Returna+b, fora andb numbers.
operator.and_(a,b)
operator.__and__(a,b)
Return the bitwise and ofa andb.
operator.div(a,b)
operator.__div__(a,b)
Returna/b when__future__.division is not in effect. This isalso known as “classic” division.
operator.floordiv(a,b)
operator.__floordiv__(a,b)

Returna//b.

New in version 2.2.

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

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

New in version 2.0:The namesinvert() and__invert__().

operator.lshift(a,b)
operator.__lshift__(a,b)
Returna shifted left byb.
operator.mod(a,b)
operator.__mod__(a,b)
Returna%b.
operator.mul(a,b)
operator.__mul__(a,b)
Returna*b, fora andb numbers.
operator.neg(obj)
operator.__neg__(obj)
Returnobj negated.
operator.or_(a,b)
operator.__or__(a,b)
Return the bitwise or ofa andb.
operator.pos(obj)
operator.__pos__(obj)
Returnobj positive.
operator.pow(a,b)
operator.__pow__(a,b)

Returna**b, fora andb numbers.

New in version 2.3.

operator.rshift(a,b)
operator.__rshift__(a,b)
Returna shifted right byb.
operator.sub(a,b)
operator.__sub__(a,b)
Returna-b.
operator.truediv(a,b)
operator.__truediv__(a,b)

Returna/b when__future__.division is in effect. This is alsoknown as “true” division.

New in version 2.2.

operator.xor(a,b)
operator.__xor__(a,b)
Return the bitwise exclusive or ofa andb.
operator.index(a)
operator.__index__(a)

Returna converted to an integer. Equivalent toa.__index__().

New in version 2.5.

Operations which work with sequences include:

operator.concat(a,b)
operator.__concat__(a,b)
Returna+b fora andb sequences.
operator.contains(a,b)
operator.__contains__(a,b)

Return the outcome of the testbina. Note the reversed operands.

New in version 2.0:The name__contains__().

operator.countOf(a,b)
Return the number of occurrences ofb ina.
operator.delitem(a,b)
operator.__delitem__(a,b)
Remove the value ofa at indexb.
operator.delslice(a,b,c)
operator.__delslice__(a,b,c)
Delete the slice ofa from indexb to indexc-1.
operator.getitem(a,b)
operator.__getitem__(a,b)
Return the value ofa at indexb.
operator.getslice(a,b,c)
operator.__getslice__(a,b,c)
Return the slice ofa from indexb to indexc-1.
operator.indexOf(a,b)
Return the index of the first of occurrence ofb ina.
operator.repeat(a,b)
operator.__repeat__(a,b)
Returna*b wherea is a sequence andb is an integer.
operator.sequenceIncludes(...)

Deprecated since version 2.0:Usecontains() instead.

Alias forcontains().

operator.setitem(a,b,c)
operator.__setitem__(a,b,c)
Set the value ofa at indexb toc.
operator.setslice(a,b,c,v)
operator.__setslice__(a,b,c,v)
Set the slice ofa from indexb to indexc-1 to the sequencev.

Many operations have an “in-place” version. The following functions provide amore primitive access to in-place operators than the usual syntax does; forexample, thestatementx+=y is equivalent tox=operator.iadd(x,y). Another way to put it is to say thatz=operator.iadd(x,y) is equivalent to the compound statementz=x;z+=y.

operator.iadd(a,b)
operator.__iadd__(a,b)

a=iadd(a,b) is equivalent toa+=b.

New in version 2.5.

operator.iand(a,b)
operator.__iand__(a,b)

a=iand(a,b) is equivalent toa&=b.

New in version 2.5.

operator.iconcat(a,b)
operator.__iconcat__(a,b)

a=iconcat(a,b) is equivalent toa+=b fora andb sequences.

New in version 2.5.

operator.idiv(a,b)
operator.__idiv__(a,b)

a=idiv(a,b) is equivalent toa/=b when__future__.division isnot in effect.

New in version 2.5.

operator.ifloordiv(a,b)
operator.__ifloordiv__(a,b)

a=ifloordiv(a,b) is equivalent toa//=b.

New in version 2.5.

operator.ilshift(a,b)
operator.__ilshift__(a,b)

a=ilshift(a,b) is equivalent toa<<=b.

New in version 2.5.

operator.imod(a,b)
operator.__imod__(a,b)

a=imod(a,b) is equivalent toa%=b.

New in version 2.5.

operator.imul(a,b)
operator.__imul__(a,b)

a=imul(a,b) is equivalent toa*=b.

New in version 2.5.

operator.ior(a,b)
operator.__ior__(a,b)

a=ior(a,b) is equivalent toa|=b.

New in version 2.5.

operator.ipow(a,b)
operator.__ipow__(a,b)

a=ipow(a,b) is equivalent toa**=b.

New in version 2.5.

operator.irepeat(a,b)
operator.__irepeat__(a,b)

a=irepeat(a,b) is equivalent toa*=b wherea is a sequence andb is an integer.

New in version 2.5.

operator.irshift(a,b)
operator.__irshift__(a,b)

a=irshift(a,b) is equivalent toa>>=b.

New in version 2.5.

operator.isub(a,b)
operator.__isub__(a,b)

a=isub(a,b) is equivalent toa-=b.

New in version 2.5.

operator.itruediv(a,b)
operator.__itruediv__(a,b)

a=itruediv(a,b) is equivalent toa/=b when__future__.divisionis in effect.

New in version 2.5.

operator.ixor(a,b)
operator.__ixor__(a,b)

a=ixor(a,b) is equivalent toa^=b.

New in version 2.5.

Theoperator module also defines a few predicates to test the type ofobjects.

Note

Be careful not to misinterpret the results of these functions; onlyisCallable() has any measure of reliability with instance objects.For example:

>>>classC:...pass...>>>importoperator>>>obj=C()>>>operator.isMappingType(obj)True

Note

Python 3 is expected to introduce abstract base classes forcollection types, so it should be possible to write, for example,isinstance(obj,collections.Mapping) andisinstance(obj,collections.Sequence).

operator.isCallable(obj)

Deprecated since version 2.0:Use thecallable() built-in function instead.

Returns true if the objectobj can be called like a function, otherwise itreturns false. True is returned for functions, bound and unbound methods, classobjects, and instance objects which support the__call__() method.

operator.isMappingType(obj)

Returns true if the objectobj supports the mapping interface. This is true fordictionaries and all instance objects defining__getitem__().

Warning

There is no reliable way to test if an instance supports the complete mappingprotocol since the interface itself is ill-defined. This makes this test lessuseful than it otherwise might be.

operator.isNumberType(obj)

Returns true if the objectobj represents a number. This is true for allnumeric types implemented in C.

Warning

There is no reliable way to test if an instance supports the complete numericinterface since the interface itself is ill-defined. This makes this test lessuseful than it otherwise might be.

operator.isSequenceType(obj)

Returns true if the objectobj supports the sequence protocol. This returns truefor all objects which define sequence methods in C, and for all instance objectsdefining__getitem__().

Warning

There is no reliable way to test if an instance supports the complete sequenceinterface since the interface itself is ill-defined. This makes this test lessuseful than it otherwise might be.

Example: Build a dictionary that maps the ordinals from0 to255 totheir character equivalents.

>>>d={}>>>keys=range(256)>>>vals=map(chr,keys)>>>map(operator.setitem,[d]*len(keys),keys,vals)# doctest: +SKIP

Theoperator module also defines tools for generalized attribute and itemlookups. These are useful for making fast field extractors as arguments formap(),sorted(),itertools.groupby(), or other functions thatexpect a function argument.

operator.attrgetter(attr[,args...])

Return a callable object that fetchesattr from its operand. If more than oneattribute is requested, returns a tuple of attributes. After,f=attrgetter('name'), the callf(b) returnsb.name. After,f=attrgetter('name','date'), the callf(b) returns(b.name,b.date).

The attribute names can also contain dots; afterf=attrgetter('date.month'),the callf(b) returnsb.date.month.

New in version 2.4.

Changed in version 2.5:Added support for multiple attributes.

Changed in version 2.6:Added support for dotted attributes.

operator.itemgetter(item[,args...])

Return a callable object that fetchesitem from its operand using theoperand’s__getitem__() method. If multiple items are specified,returns a tuple of lookup values. Equivalent to:

defitemgetter(*items):iflen(items)==1:item=items[0]defg(obj):returnobj[item]else:defg(obj):returntuple(obj[item]foriteminitems)returng

The items can be any type accepted by the operand’s__getitem__()method. Dictionaries accept any hashable value. Lists, tuples, andstrings accept an index or a slice:

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

New in version 2.4.

Changed in version 2.5:Added support for multiple item extraction.

Example of usingitemgetter() to retrieve specific fields from atuple record:

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

Return a callable object that calls the methodname on its operand. Ifadditional arguments and/or keyword arguments are given, they will be givento the method as well. Afterf=methodcaller('name'), the callf(b)returnsb.name(). Afterf=methodcaller('name','foo',bar=1), thecallf(b) returnsb.name('foo',bar=1).

New in version 2.6.

Mapping Operators to Functions

This table shows how abstract operations correspond to operator symbols in thePython syntax and the functions in theoperator module.

OperationSyntaxFunction
Additiona+badd(a,b)
Concatenationseq1+seq2concat(seq1,seq2)
Containment Testobjinseqcontains(seq,obj)
Divisiona/bdiv(a,b) (without__future__.division)
Divisiona/btruediv(a,b) (with__future__.division)
Divisiona//bfloordiv(a,b)
Bitwise Anda&band_(a,b)
Bitwise Exclusive Ora^bxor(a,b)
Bitwise Inversion~ainvert(a)
Bitwise Ora|bor_(a,b)
Exponentiationa**bpow(a,b)
Identityaisbis_(a,b)
Identityaisnotbis_not(a,b)
Indexed Assignmentobj[k]=vsetitem(obj,k,v)
Indexed Deletiondelobj[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)notanot_(a)
Right Shifta>>brshift(a,b)
Sequence Repetitionseq*irepeat(seq,i)
Slice Assignmentseq[i:j]=valuessetslice(seq,i,j,values)
Slice Deletiondelseq[i:j]delslice(seq,i,j)
Slicingseq[i:j]getslice(seq,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)

Table Of Contents

Previous topic

functools — Higher order functions and operations on callable objects

Next topic

File and Directory Access

This Page

Quick search

Navigation

©Copyright 1990-2008, Python Software Foundation. Last updated on Oct 02, 2008. Created usingSphinx 0.5.

[8]ページ先頭

©2009-2026 Movatter.jp