The operator module contains various built-in operators of Python, such as logic, comparison, and calculation. here we will summarize the examples of using operators of the operator module in Python for some common operators: the operator module is a built-in operator function interface in python, which defines some arithmetic and relatively built-in operation functions. The operator module is implemented in c, so the execution speed is faster than that of python code.
Logical operation
from operator import *a = [1, 2, 3]b = aprint 'a =', aprint 'b =', bprint print 'not_(a) :', not_(a)print 'truth(a) :', truth(a)print 'is_(a, b) :', is_(a, b)print 'is_not(a, b) :', is_not(a, b)
Print result:
a = [1, 2, 3]b = [1, 2, 3]not_(a) : Falsetruth(a) : Trueis_(a, b) : Trueis_not(a, b): False
The result shows that some operator operation functions are the same as those of the original operation.
Comparison operator
Operator provides a wide range of comparative operations.
a = 3b = 5print 'a =', aprint 'b =', bprint for func in (lt, le, eq, ne, ge, gt): print '{0}(a, b):'.format(func.__name__), func(a, b)
Print results
a = 3b = 5lt(a, b): Truele(a, b): Trueeq(a, b): Falsene(a, b): Truege(a, b): Falsegt(a, b): False
These functions are equivalent to the expression syntax of <=, ==, >=, and>.
Arithmetic operators
Arithmetic operators that process numbers are also supported.
a, b, c, d = -1, 2, -3, 4print 'a =', aprint 'b =', bprint 'c =', cprint 'd =', d print '\nPositive/Negative:'print 'abs(a):', abs(a)print 'neg(a):', neg(a)print 'neg(b):', neg(b)print 'pos(a):', pos(a)print 'pos(b):', pos(b)
Print results
a = -1b = 2c = -3d = 4Positive/Negative:abs(a): 1neg(a): 1neg(b): -2pos(a): -1pos(b): 2
Abs returns the absolute value, neg returns (-obj), and pos returns (+ obj ).
a = -2b = 5.0print 'a =', aprint 'b =', b print '\nArithmetic'print 'add(a, b) :', add(a, b)print 'p(a, b) :', p(a, b)print 'floorp(a, b) :', floorp(a, b)print 'mod(a, b) :', mod(a, b)print 'mul(a, b) :', mul(a, b)print 'pow(a, b) :', pow(a, b)print 'sub(a, b) :', sub(a, b)print 'truep(a, b) :', truep(a, b)
Print results
A =-2b = 5.0 Arithmeticadd (a, B): 3.0 p (a, B):-0.4 floorp (a, B):-1.0mod (a, B ): 3.0 # View negative number modulo mul (a, B):-10.0pow (a, B):-32.0sub (a, B):-7.0 truep (a, B):-0.4
Mod indicates Modulo, mul indicates multiplication, pow indicates power, and sub indicates subtraction
a = 2b = 6print 'a =', aprint 'b =', bprint '\nBitwise:'print 'and_(a, b) :', and_(a, b)print 'invert(a) :', invert(a)print 'lshift(a, b) :', lshift(a, b)print 'or_(a, b) :', or_(a, b)print 'rshift(a, b) :', rshift(a, b)print 'xor(a, b) :', xor(a, b)
Print results
a = 2b = 6Bitwise:and_(a, b) : 2invert(a) : -3lshift(a, b) : 128or_(a, b) : 6rshift(a, b) : 0xor(a, b) : 4
And indicates bitwise and, invert indicates the inverse operation, lshift indicates the left displacement, or indicates the bitwise or, rshift indicates the right displacement, and xor indicates the bitwise xor.
In-situ operator
That is, the in-place operation. x + = y is equivalent to x = iadd (x, y). if it is copied to other variables such as z = iadd (x, y) it is equivalent to z = x; z + = y.
a = 3b = 4c = [1, 2]d = ['a', 'b']print 'a =', aprint 'b =', bprint 'c =', cprint 'd =', dprinta = iadd(a, b)print 'a = iadd(a, b) =>', aprintc = iconcat(c, d)print 'c = iconcat(c, d) =>', c
How to obtain attributes and elements
One of the most special features of the operator module is the concept of obtaining methods. the obtaining methods are some callable objects constructed during runtime to obtain the attributes or sequences of objects, obtaining methods are particularly useful when processing the Iterator or generator sequence. the overhead they introduce will greatly reduce the overhead of lambda or Python functions.
from operator import *class MyObj(object): def __init__(self, arg): super(MyObj, self).__init__() self.arg = arg def __repr__(self): return 'MyObj(%s)' % self.argobjs = [MyObj(i) for i in xrange(5)]print "Object:", objsg = attrgetter("arg")vals = [g(i) for i in objs]print "arg values:", valsobjs.reverse()print "reversed:", objsprint "sorted:", sorted(objs, key=g)
Result:
Object: [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]arg values: [0, 1, 2, 3, 4]reversed: [MyObj(4), MyObj(3), MyObj(2), MyObj(1), MyObj(0)]sorted: [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]
The property acquisition method is similar
lambda x, n='attrname':getattr(x,nz)
The element acquisition method is similar
lambda x,y=5:x[y]
from operator import *l = [dict(val=-1*i) for i in xrange(4)]print "dictionaries:", lg = itemgetter("val")vals = [g(i) for i in l]print "values: ", valsprint "sorted:", sorted(l, key=g)l = [(i,i*-2) for i in xrange(4)]print "tuples: ", lg = itemgetter(1)vals = [g(i) for i in l]print "values:", valsprint "sorted:", sorted(l, key=g)
The result is as follows:
dictionaries: [{'val': 0}, {'val': -1}, {'val': -2}, {'val': -3}]values: [0, -1, -2, -3]sorted: [{'val': -3}, {'val': -2}, {'val': -1}, {'val': 0}]tuples: [(0, 0), (1, -2), (2, -4), (3, -6)]values: [0, -2, -4, -6]sorted: [(3, -6), (2, -4), (1, -2), (0, 0)]
In addition to sequences, the element acquisition method also applies to ING.
Combine operators and custom classes
Functions in the operator module work through standard Python interfaces for corresponding operations. Therefore, they are applicable not only to built-in types, but also to user-defined types.
from operator import *class MyObj(object): def __init__(self, val): super(MyObj, self).__init__() self.val = val return def __str__(self): return "MyObj(%s)" % self.val def __lt__(self, other): return self.val < other.val def __add__(self, other): return MyObj(self.val + other.val)a = MyObj(1)b = MyObj(2)print lt(a, b)print add(a,b)
The result is as follows:
TrueMyObj(3)
Type check
The operator module also contains functions to test the API compatibility of ING, numbers, and sequence types.
from operator import *class NoType(object): passclass MultiType(object): def __len__(self): return 0 def __getitem__(self, name): return "mapping" def __int__(self): return 0o = NoType()t = MultiType()for func in [isMappingType, isNumberType, isSequenceType]: print "%s(o):" % func.__name__, func(o) print "%s(t):" % func.__name__, func(t)
The result is as follows:
isMappingType(o): FalseisMappingType(t): TrueisNumberType(o): FalseisNumberType(t): TrueisSequenceType(o): FalseisSequenceType(t): True
However, these tests are not complete, because the excuses are not strictly defined.
Get object method
You can use methodcaller to obtain objects.
From operator import methodcallerclass Student (object): def _ init _ (self, name): self. name = name def getName (self): return self. namestu = Student ("Jim") func = methodcaller ('getname') print func (stu) # output Jim
You can also pass parameters to the method:
F = methodcaller ('name', 'foo', bar = 1) f (B) # return B. name ('foo', bar = 1) the methodcaller method is equivalent to the following function: def methodcaller (name, * args, ** kwargs): def caller (obj ): return getattr (obj, name) (* args, ** kwargs) return caller
For more articles about using operators in the operator module in Python, refer to the PHP Chinese network!