[Python标准库]operator——内置操作符的函数接口

[Python标准库]operator——内置操作符的函数接口
        作用:内置操作符的函数接口。
        Python 版本:1.4 及以后版本
        使用迭代器编程时,有时需要为简单的表达式创建小函数。有些情况下,这些确实可以实现为 lambda 函数,不过对于某些操作根本不需要新函数。operator 模块定义了一些对应算术和比较内置操作的函数。
逻辑操作
        有一些函数可以用来确定一个值的相应 Boolean 值,将其取反来创建相反的 Boolean 值,以及比较对象查看它们是否相等。

  
  
  1. from operator import *
  2. a = -1
  3. b = 5
  4. print 'a =', a
  5. print 'b =', b
  6. print
  7. print 'not_(a) :', not_(a)
  8. print 'truth(a) :', truth(a)
  9. print 'is_(a, b) :', is_(a, b)
  10. print 'is_not(a, b):', is_not(a, b)
        not_() 后面有下划线,因为 not 是一个 Python 关键字。truth() 会应用 if 语句中测试一个表达式时所用的同样的逻辑。is_() 实现了 is 关键字使用的相同检查,is_not() 完成同样的测试,但返回相反的答案。
比较操作符
        所有富比较操作符都得到支持。

  
  
  1. from operator import *
  2. a = 1
  3. b = 5.0
  4. print 'a =', a
  5. print 'b =', b
  6. for func in (lt, le, eq, ne, ge, gt):
  7. print '%s(a, b):' % func.__name__, func(a, b)
        这些函数等价于使用 <、<=、==、>= 和 > 的表达式语法。
算术操作符
        处理数字值的算术操作符也得到支持。

  
  
  1. from operator import *
  2. a = -1
  3. b = 5.0
  4. c = 2
  5. d = 6
  6. print 'a =', a
  7. print 'b =', b
  8. print 'c =', c
  9. print 'd =', d
  10. print '\nPositive/Negative:'
  11. print 'abs(a):', abs(a)
  12. print 'neg(a):', neg(a)
  13. print 'neg(b):', neg(b)
  14. print 'pos(a):', pos(a)
  15. print 'pos(b):', pos(b)
  16. print '\nArithmetic:'
  17. print 'add(a, b) :', add(a, b)
  18. print 'div(a, b) :', div(a, b)
  19. print 'div(d, c) :', div(d, c)
  20. print 'floordiv(a, b):', floordiv(a, b)
  21. print 'floordiv(d, c):', floordiv(d, c)
  22. print 'mod(a, b) :', mod(a, b)
  23. print 'mul(a, b) :', mul(a, b)
  24. print 'pow(c, d) :', pow(c, d)
  25. print 'sub(b, a) :', sub(b, a)
  26. print 'truediv(a, b) :', truediv(a, b)
  27. print 'truediv(d, c) :', truediv(d, c)
  28. print '\nBitwise:'
  29. print 'and_(c, d) :', and_(c, d)
  30. print 'invert(c) :', invert(c)
  31. print 'lshift(c, d):', lshift(c, d)
  32. print 'or_(c, d) :', or_(c, d)
  33. print 'rshift(d, c):', rshift(d, c)
  34. print 'xor(c, d) :', xor(c, d)
        有两个不同的除法操作符:floordiv()(Python 3.0 版本之前实现的整数除法)和 truediv()(浮点数除法)。
序列操作符
        处理序列的操作符可以划分为 4 组:建立序列、搜索元素、访问内容和从序列删除元素。

  
  
  1. from operator import *
  2. a = [ 1, 2, 3 ]
  3. b = [ 'a', 'b', 'c' ]
  4. print 'a =', a
  5. print 'b =', b
  6. print '\nConstructive:'
  7. print ' concat(a, b):', concat(a, b)
  8. print ' repeat(a, 3):', repeat(a, 3)
  9. print '\nSearching:'
  10. print ' contains(a, 1) :', contains(a, 1)
  11. print ' contains(b, "d"):', contains(b, "d")
  12. print ' countOf(a, 1) :', countOf(a, 1)
  13. print ' countOf(b, "d") :', countOf(b, "d")
  14. print ' indexOf(a, 5) :', indexOf(a, 1)
  15. print '\nAccess Items:'
  16. print ' getitem(b, 1) :', getitem(b, 1)
  17. print ' getslice(a, 1, 3) :', getslice(a, 1, 3)
  18. print ' setitem(b, 1, "d") :', setitem(b, 1, "d"),
  19. print ', after b =', b
  20. print ' setslice(a, 1, 3, [4, 5]):', setslice(a, 1, 3, [ 4, 5]),
  21. print ', after a =', a
  22. print '\nDestructive:'
  23. print ' delitem(b, 1) :', delitem(b, 1), ', after b =', b
  24. print ' delslice(a, 1, 3):', delslice(a, 1, 3), ', after a=', a
        其中一些操作(如 setitem() 和 delitem())会原地修改序列,而不返回任何值。
原地操作符
        除了标准操作符外,很多对象类型还通过一些特殊操作符(如 +=)支持“原地”修改。这些原地修改也有相应的等价函数。

  
  
  1. from operator import *
  2. a = -1
  3. b = 5.0
  4. c = [ 1, 2, 3]
  5. d = [ 'a', 'b', 'c' ]
  6. print 'a =', a
  7. print 'b =', b
  8. print 'c =', c
  9. print 'd =', d
  10. print
  11. a = iadd(a, b)
  12. print 'a = iadd(a, b) =>', a
  13. print
  14. c = iconcat(c, d)
  15. print 'c = oconcat(c, d) =>', c
        这些例子只展示了部分函数。
属性和元素“获取方法”
        operator 模块最特别的特性之一是获取方法(getter)的概念。获取方法是运行时构造的一些可回调对象,用来获取对象的属性或序列的内容。获取方法在处理迭代器或生成器序列时特别有用,它们引入的开销会大大低于 lambda 或 Python 函数的开销。

  
  
  1. from operator import *
  2. class MyObj(object):
  3. """example class for attrgetter"""
  4. def __init__(self, arg):
  5. super(MyObj, self).__init__()
  6. self.arg = arg
  7. def __repr__(self):
  8. return 'MyObj(%s)' % self.arg
  9. l = [ MyObj(i) for i in xrange( 5) ]
  10. print 'objects :', l
  11. # Extract thr 'arg' value from each object
  12. g = attrgetter( 'arg')
  13. vals = [ g(i) for i in l ]
  14. print 'arg values:', vals
  15. # Sort using arg
  16. l.reverse()
  17. print 'reversed :', l
  18. print 'sorted :', sorted(l, key=g)
        属性获取方法的工作类似于 lambda x, n='attrname':getattr(x, n);
        元素获取方法的工作类似于 lambda x, y=5: x[y];

  
  
  1. from operator import *
  2. l = [ dict(val= -1 * i) for i in xrange( 4) ]
  3. print 'Dictionaries:', l
  4. g = itemgetter( 'val')
  5. vals = [ g(i) for i in l ]
  6. print ' values:', vals
  7. print ' sorted:', sorted(l, key=g)
  8. print
  9. l = [ (i, i* -2) for i in xrange( 4) ]
  10. print 'Tuples :', l
  11. g = itemgetter( 1)
  12. vals = [ g(i) for i in l ]
  13. print ' values:', vals
  14. print ' sorted:', sorted(l, key=g)
        除了序列外,元素获取方法还适用于映射。
结合操作符和定制类
        operator 模块中的函数通过相应操作的标准 Python 接口完成工作,所以它们不仅适用于内置类型,还适用于用户定义的类。

  
  
  1. from operator import *
  2. class MyObj(object):
  3. """example class for attrgetter"""
  4. def __init__(self, val):
  5. super(MyObj, self).__init__()
  6. self.val = val
  7. return
  8. def __str__(self):
  9. return 'MyObj(%s)' % self.val
  10. def __lt__(self, other):
  11. """compare for less-than"""
  12. print 'Testing %s < %s' % (self, other)
  13. return self.val < other.val
  14. def __add__(self, other):
  15. """add values"""
  16. print 'Adding %s + %s' % (self, other)
  17. return MyObj(self.val + other.val)
  18. a = MyObj( 1)
  19. b = MyObj( 2)
  20. print 'Comparison:'
  21. print lt(a, b)
  22. print '\nArithmetic:'
  23. print add(a, b)
类型检查
        operator 模块还包含一些函数来测试映射、数字和序列的 API 兼容性。

  
  
  1. from operator import *
  2. class NoType(object):
  3. """Supports none of the type APIs"""
  4. class MultiType(object):
  5. """Supports multiple type APIs"""
  6. def __len__(slef):
  7. return 0
  8. def __getitem__(slef, name):
  9. return 'mapping'
  10. def __int__(self):
  11. return 0
  12. o = NoType()
  13. t = MultiType()
  14. for func in (isMappingType, isNumberType, isSequenceType):
  15. print '%s(o):' % func.__name__, func(o)
  16. print '%s(t):' % func.__name__, func(t)
        这些测试并不完善,因为接口没有严格定义,不过通过这些测试,确实能让我们对支持哪些功能有所了解。
[添加链接描述](https://blog.csdn.net/dapeng0802/article/details/50490283)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值