python中operator模块的操作符使用

operator模块是python中内置的操作符函数接口，它定义了一些算术和比较内置操作的函数。operator模块是用c实现的，所以执行速度比python代码快。

from operator import *
a = [1, 2, 3]
b = a
print ‘a =’, a
print ‘b =’, b
print
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)

a = [1, 2, 3]
b = [1, 2, 3]
not_(a) : false
truth(a) : true
is_(a, b) : true
is_not(a, b): false

a = 3
b = 5
print ‘a =’, a
print ‘b =’, b
print
for func in (lt, le, eq, ne, ge, gt):
print ‘{0}(a, b):’.format(func.__name__), func(a, b)

a = 3
b = 5
lt(a, b): true
le(a, b): true
eq(a, b): false
ne(a, b): true
ge(a, b): false
gt(a, b): false

a, b, c, d = -1, 2, -3, 4
print ‘a =’, a
print ‘b =’, b
print ‘c =’, c
print ‘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)

a = -1
b = 2
c = -3
d = 4
positive/negative:
abs(a): 1
neg(a): 1
neg(b): -2
pos(a): -1
pos(b): 2

abs返回值得绝对值，neg返回(-obj), pos返回(+obj)。

a = -2
b = 5.0
print ‘a =’, a
print ‘b =’, b
print ‘\narithmetic’
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)

a = -2
b = 5.0
arithmetic
p(a, b) : -0.4
floorp(a, b) : -1.0
mod(a, b) : 3.0 # 查看负数取模
mul(a, b) : -10.0
pow(a, b) : -32.0
sub(a, b) : -7.0
truep(a, b) : -0.4

mod表示取模， mul 表示相乘，pow是次方, sub表示相减

a = 2
b = 6
print ‘a =’, a
print ‘b =’, b
print ‘\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)

a = 2
b = 6
bitwise:
and_(a, b) : 2
invert(a) : -3
lshift(a, b) : 128
or_(a, b) : 6
rshift(a, b) : 0
xor(a, b) : 4

and 表示按位与, invert 表示取反操作, lshift表示左位移, or表示按位或, rshift表示右位移,xor表示按位异或。

a = 3
b = 4
c = [1, 2]
d = [‘a’, ‘b’]
print ‘a =’, a
print ‘b =’, b
print ‘c =’, c
print ‘d =’, d
print
print ‘a = iadd(a, b) =>’, a
print
c = iconcat(c, d)
print ‘c = iconcat(c, d) =>’, c

from operator import *
class myobj(object):
def __init__(self, arg):
super(myobj, self).__init__()
self.arg = arg
def __repr__(self):
return ‘myobj(%s)’ % self.arg
objs = [myobj(i) for i in xrange(5)]
print “object:”, objs
g = attrgetter(“arg”)
vals = [g(i) for i in objs]
print “arg values:”, vals
objs.reverse()
print “reversed:”, objs
print “sorted:”, sorted(objs, key=g)

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

lambda x, n=’attrname’:getattr(x,nz）

lambda x,y=5:x[y]

from operator import *
l = [dict(val=-1*i) for i in xrange(4)]
print “dictionaries:”, l
g = itemgetter(“val”)
vals = [g(i) for i in l]
print “values: “, vals
print “sorted:”, sorted(l, key=g)
l = [(i,i*-2) for i in xrange(4)]
print “tuples: “, l
g = itemgetter(1)
vals = [g(i) for i in l]
print “values:”, vals
print “sorted:”, sorted(l, key=g)

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

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)

true
myobj(3)

from operator import *
class notype(object):
pass
class multitype(object):
def __len__(self):
return 0
def __getitem__(self, name):
return “mapping”
def __int__(self):
return 0
o = notype()
t = multitype()
for func in [ismappingtype, isnumbertype, issequencetype]:
print “%s(o):” % func.__name__, func(o)
print “%s(t):” % func.__name__, func(t)

ismappingtype(o): false
ismappingtype(t): true
isnumbertype(o): false
isnumbertype(t): true
issequencetype(o): false
issequencetype(t): true

from operator import methodcaller
class student(object):
def __init__(self, name):
self.name = name
def getname(self):
return self.name
stu = student(“jim”)
func = methodcaller(‘getname’)
print func(stu) # 输出jim

f=methodcaller(‘name’, ‘foo’, bar=1)
f(b) # return b.name(‘foo’, bar=1)
methodcaller方法等价于下面这个函数：
def methodcaller(name, *args, **kwargs):
def caller(obj):
return getattr(obj, name)(*args, **kwargs)
return caller

Posted in 未分类