[Python标准库]operator——内置操作符的函数接口
2016-01-09 23:13
567 查看
[Python标准库]operator——内置操作符的函数接口
作用:内置操作符的函数接口。
Python 版本:1.4 及以后版本
使用迭代器编程时,有时需要为简单的表达式创建小函数。有些情况下,这些确实可以实现为 lambda 函数,不过对于某些操作根本不需要新函数。operator 模块定义了一些对应算术和比较内置操作的函数。
逻辑操作
有一些函数可以用来确定一个值的相应 Boolean 值,将其取反来创建相反的 Boolean 值,以及比较对象查看它们是否相等。
not_() 后面有下划线,因为 not 是一个 Python 关键字。truth() 会应用 if 语句中测试一个表达式时所用的同样的逻辑。is_() 实现了 is 关键字使用的相同检查,is_not() 完成同样的测试,但返回相反的答案。
比较操作符
所有富比较操作符都得到支持。
这些函数等价于使用 <、<=、==、>= 和 > 的表达式语法。
算术操作符
处理数字值的算术操作符也得到支持。
有两个不同的除法操作符:floordiv()(Python 3.0 版本之前实现的整数除法)和 truediv()(浮点数除法)。
序列操作符
处理序列的操作符可以划分为 4 组:建立序列、搜索元素、访问内容和从序列删除元素。
其中一些操作(如 setitem() 和 delitem())会原地修改序列,而不返回任何值。
原地操作符
除了标准操作符外,很多对象类型还通过一些特殊操作符(如 +=)支持“原地”修改。这些原地修改也有相应的等价函数。
这些例子只展示了部分函数。
属性和元素“获取方法”
operator 模块最特别的特性之一是获取方法(getter)的概念。获取方法是运行时构造的一些可回调对象,用来获取对象的属性或序列的内容。获取方法在处理迭代器或生成器序列时特别有用,它们引入的开销会大大低于 lambda 或 Python 函数的开销。
属性获取方法的工作类似于 lambda x, n='attrname':getattr(x, n);
元素获取方法的工作类似于 lambda x, y=5: x[y];
除了序列外,元素获取方法还适用于映射。
结合操作符和定制类
operator 模块中的函数通过相应操作的标准 Python 接口完成工作,所以它们不仅适用于内置类型,还适用于用户定义的类。
类型检查
operator 模块还包含一些函数来测试映射、数字和序列的 API 兼容性。
这些测试并不完善,因为接口没有严格定义,不过通过这些测试,确实能让我们对支持哪些功能有所了解。
作用:内置操作符的函数接口。
Python 版本:1.4 及以后版本
使用迭代器编程时,有时需要为简单的表达式创建小函数。有些情况下,这些确实可以实现为 lambda 函数,不过对于某些操作根本不需要新函数。operator 模块定义了一些对应算术和比较内置操作的函数。
逻辑操作
有一些函数可以用来确定一个值的相应 Boolean 值,将其取反来创建相反的 Boolean 值,以及比较对象查看它们是否相等。
from operator import * a = -1 b = 5 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)
not_() 后面有下划线,因为 not 是一个 Python 关键字。truth() 会应用 if 语句中测试一个表达式时所用的同样的逻辑。is_() 实现了 is 关键字使用的相同检查,is_not() 完成同样的测试,但返回相反的答案。
比较操作符
所有富比较操作符都得到支持。
from operator import * a = 1 b = 5.0 print 'a =', a print 'b =', b for func in (lt, le, eq, ne, ge, gt): print '%s(a, b):' % func.__name__, func(a, b)
这些函数等价于使用 <、<=、==、>= 和 > 的表达式语法。
算术操作符
处理数字值的算术操作符也得到支持。
from operator import * a = -1 b = 5.0 c = 2 d = 6 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) print '\nArithmetic:' print 'add(a, b) :', add(a, b) print 'div(a, b) :', div(a, b) print 'div(d, c) :', div(d, c) print 'floordiv(a, b):', floordiv(a, b) print 'floordiv(d, c):', floordiv(d, c) print 'mod(a, b) :', mod(a, b) print 'mul(a, b) :', mul(a, b) print 'pow(c, d) :', pow(c, d) print 'sub(b, a) :', sub(b, a) print 'truediv(a, b) :', truediv(a, b) print 'truediv(d, c) :', truediv(d, c) print '\nBitwise:' print 'and_(c, d) :', and_(c, d) print 'invert(c) :', invert(c) print 'lshift(c, d):', lshift(c, d) print 'or_(c, d) :', or_(c, d) print 'rshift(d, c):', rshift(d, c) print 'xor(c, d) :', xor(c, d)
有两个不同的除法操作符:floordiv()(Python 3.0 版本之前实现的整数除法)和 truediv()(浮点数除法)。
序列操作符
处理序列的操作符可以划分为 4 组:建立序列、搜索元素、访问内容和从序列删除元素。
from operator import * a = [ 1, 2, 3 ] b = [ 'a', 'b', 'c' ] print 'a =', a print 'b =', b print '\nConstructive:' print ' concat(a, b):', concat(a, b) print ' repeat(a, 3):', repeat(a, 3) print '\nSearching:' print ' contains(a, 1) :', contains(a, 1) print ' contains(b, "d"):', contains(b, "d") print ' countOf(a, 1) :', countOf(a, 1) print ' countOf(b, "d") :', countOf(b, "d") print ' indexOf(a, 5) :', indexOf(a, 1) print '\nAccess Items:' print ' getitem(b, 1) :', getitem(b, 1) print ' getslice(a, 1, 3) :', getslice(a, 1, 3) print ' setitem(b, 1, "d") :', setitem(b, 1, "d"), print ', after b =', b print ' setslice(a, 1, 3, [4, 5]):', setslice(a, 1, 3, [4, 5]), print ', after a =', a print '\nDestructive:' print ' delitem(b, 1) :', delitem(b, 1), ', after b =', b print ' delslice(a, 1, 3):', delslice(a, 1, 3), ', after a=', a
其中一些操作(如 setitem() 和 delitem())会原地修改序列,而不返回任何值。
原地操作符
除了标准操作符外,很多对象类型还通过一些特殊操作符(如 +=)支持“原地”修改。这些原地修改也有相应的等价函数。
from operator import * a = -1 b = 5.0 c = [ 1, 2, 3] d = [ 'a', 'b', 'c' ] print 'a =', a print 'b =', b print 'c =', c print 'd =', d print a = iadd(a, b) print 'a = iadd(a, b) =>', a print c = iconcat(c, d) print 'c = oconcat(c, d) =>', c
这些例子只展示了部分函数。
属性和元素“获取方法”
operator 模块最特别的特性之一是获取方法(getter)的概念。获取方法是运行时构造的一些可回调对象,用来获取对象的属性或序列的内容。获取方法在处理迭代器或生成器序列时特别有用,它们引入的开销会大大低于 lambda 或 Python 函数的开销。
from operator import * class MyObj(object): """example class for attrgetter""" def __init__(self, arg): super(MyObj, self).__init__() self.arg = arg def __repr__(self): return 'MyObj(%s)' % self.arg l = [ MyObj(i) for i in xrange(5) ] print 'objects :', l # Extract thr 'arg' value from each object g = attrgetter('arg') vals = [ g(i) for i in l ] print 'arg values:', vals # Sort using arg l.reverse() print 'reversed :', l print 'sorted :', sorted(l, key=g)
属性获取方法的工作类似于 lambda x, n='attrname':getattr(x, n);
元素获取方法的工作类似于 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) print 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)
除了序列外,元素获取方法还适用于映射。
结合操作符和定制类
operator 模块中的函数通过相应操作的标准 Python 接口完成工作,所以它们不仅适用于内置类型,还适用于用户定义的类。
from operator import * class MyObj(object): """example class for attrgetter""" def __init__(self, val): super(MyObj, self).__init__() self.val = val return def __str__(self): return 'MyObj(%s)' % self.val def __lt__(self, other): """compare for less-than""" print 'Testing %s < %s' % (self, other) return self.val < other.val def __add__(self, other): """add values""" print 'Adding %s + %s' % (self, other) return MyObj(self.val + other.val) a = MyObj(1) b = MyObj(2) print 'Comparison:' print lt(a, b) print '\nArithmetic:' print add(a, b)
类型检查
operator 模块还包含一些函数来测试映射、数字和序列的 API 兼容性。
from operator import * class NoType(object): """Supports none of the type APIs""" class MultiType(object): """Supports multiple type APIs""" def __len__(slef): return 0 def __getitem__(slef, 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)
这些测试并不完善,因为接口没有严格定义,不过通过这些测试,确实能让我们对支持哪些功能有所了解。
相关文章推荐
- Python读写文件实际操作的五大步骤
- 菜鸟学python(8) 初识函数
- Python多进程编程
- python基础学习——第二天
- 高阶函数简单总结记录
- python发送邮件方法
- python 位运算符与逻辑运算符(字符串的逻辑运算)
- 比较Python和Perl的效率
- leetcode之Reverse Linked List II
- Python中安装以及配置easy_install
- [python语法巩固][leetcode326][Power of Three]
- [python语法巩固][leetcode326][Power of Three]
- python numpy:1 numpy.array和numpy.matrix常用函数使用
- 快速打造跨平台开发环境 vagrant + virtualbox + box
- 菜鸟学python(7) 简单文件访问
- 菜鸟学python(6) for语句
- Selenium+Python Radio,Checkbox,Link,ComboBox控件
- Python修改当前工作目录
- leetcode之Partition List
- python中利用exec动态创建函数