##language:zh #pragma section-numbers on ''' ZoomQuiet 简译 ''' ::-- ZoomQuiet [<>] <> 很难相信Python 已经有15年历史了,但是作为现代开发语言,Python 不断的在增进,这里只是简要的介绍全新的2.5 版本中的特性 1. '''向下兼容''' * 尽管2.5 有很多变化,但是注意到很好的兼容己有的2.4 代码 1. '''条件语句''' * 向C/C++学习,加入了条件语句的精简形式 * 以往{{{ if x > 15: a = 1 else: a = 2 }}} * 对比C 的3项式`a = x > 15 ? 1 : 2;` * 现在Pt2.5 可以`a = 1 if x > 15 else 2` * 当然出于Py 的魔力我们可以混合数据类型来使用,比如:{{{ a = "abc" if x > 15 else 10 }}} 1. '''例外处理''' * 有关例外处理,2.5进行了轻微的改进,更多的改进讨论中,计划在3.0 实现 * 在2.4.3 使用raise {{{>>> raise "Invalid argument" Traceback (most recent call last): File "", line 1, in ? Invalid argument >>> }}} * 现在2.5 {{{>>> raise "Invalid argument" __main__:1: DeprecationWarning: raising a string exception is deprecated Traceback (most recent call last): File "", line 1, in Invalid argument >>> }}} 会多得一警报 * 现在从 `Exception` 扩展了新类`BaseException` 并从中继承出了` KeyboardInterrupt `和` SystemExit` 例外 * 随着例外处理的应用发展,现在的基本看法是: * 例外信息应该是字串 * 传入参数应该是列表或是其它集成式的对象 1. '''更佳的例外捕获''' * {{{try: test() except ZeroDivisionError: print "The expression resulted in a division-by-zero error" except Exception: print "Oops" else: print "All is good" finally: print "And everything is finished" }}} * `try`语句进行了增进,可以混合使用更多的操作关键字 1. '''回传变量发生器''' * `Generators` 机制在 2.3 被加入,在2.5 有更多的地方进行了支持 * 例如: 一含有发生器 `iterate` 的类{{{#!python class MyStuff: def __init__(self): self.a = [2,4,6,8,10,12] def iterate(self): i = 0 while i < len(self.a): yield self.a[i] i += 1 }}} * 可以类似如此应用:{{{#!python obj = MyStuff() iterate = obj.iterate() print iterate.next() print iterate.next() print iterate.next() }}} * 注意第2行从类实例返回一个`iterate`, 但是其本身没有从生成器获得参数,你需要使用 `next()` 来获取 * 在交互环境中可以观察到:{{{ >>> print iterate >>> }}} * 不同与C++ 使用反射机制来获取变量 * 这里使用 `yield` 构建了递归结构, 调用{{{ iterate.next() }}} 将进入函式段运行并返回`self.a[i]` * 再次调用`iterate.next()` , 恢复上次运行结果的 `i` ,重新进入循环,直到再次到达 `yield` 处 * 注意,使用`iterate = obj.iterate()` ; 并没有立即调用实际函式,Python 瞧见有 `yield`结构,就创建一生成器对象来代替,你可以检验这一活动,通过加入`print``{{{ def iterate(self): print "Creating iterator" i = 0 ...rest of code... }}} * 这样,在`iterate = obj.iterate()`实例化时,你是看不到 ''Creating iterator'' 输出的,只有进行`print iterate.next()` 时,才会看到 * 这种编程支持,类似特性 [[http://en.wikipedia.org/wiki/Coroutine|Coroutine]] * 使用 `close()`来指定结束;比如说,我们修订初始数组{{{ def __init__(self): self.a = [2,4,6,8,10,12, None] }}} * 通过判别`none`来结束:{{{obj = MyStuff() iterate = obj.iterate() a = iterate.next() while a != None: print a a = iterate.next() iterate.close() }}} * `close()`是2.5 中的新支持,如果你在`iterate.close()` 之后再调用'iterate.next()' 将获得一个`StopIteration`例外 * 这样的结构中,如何输入参数? 使用 `sent()`{{{#!python class MyStuff2: def __init__(self): self.a = [2,4,6,8,10,12] def iterate(self): i = 0 while i < len(self.a): val = yield self.a[i] if val == None: i += 1 else: if val < 0: val = 0 if val >= len(self.a): val = len(self.a) -1 i = val }}} * 可以这样使用{{{ >>> obj = gen1.MyStuff2() >>> i = iter(obj) >>> i.next() 2 >>> i.send(3) 8 >>> i.next() 10 }}} * 注意,有内建函式`iter()` 支持自动识别,全权替代你自定的 `iterator()`,就象预设的` __iter__()` ''有点晕…………乱译了`` 1. '''上下文管理''' * 基于提案[[http://docs.python.org/whatsnew/pep-343.html|PEP 843]] 增进了`with`功能 * {{{with open('/test.txt', 'r') as f: for line in f: process(line) }}} * 可以获得{{{>>> print f }}} 1. '''輔助改进''' * `__missing__(self, key) ` 可以来处理字典的关键字缺失 * 字串对象增加`partition`和`rpartition`函式 * 元组对象增加`startswith`和`endswith`函式 * 增强`max`和`min`{{{#!python def myord(astr): try: num = int(astr) return num except: return len(astr) }}} * 然后就可以使用进化版本的求最大{{{ print max(['abc','100','a','xyz','1'], key=myord) }}} * 更多的内置函式,比如`any()`{{{ >>> a = 10 >>> b = 20 >>> any([a>5, b>5]) True >>> any([a>50, b>50]) False >>> any([a>50, b>5]) True }}} 类似的还有`all()` * 详细可以参考[[http://docs.python.org/whatsnew/other-lang.html|其它语言方面的变化]] 1. '''库增进''' * [[http://docs.python.org/whatsnew/modules.html|追加和清退的库说明]] 1. '''专有库和DLL调用''' * {{{>>> import ctypes >>> libc = ctypes.CDLL('c:/windows/system32/user32.dll') >>> print libc.GetDesktopWindow() }}} 1. '''全面使用ElementTree处理XML''' * {{{>>> from xml.etree import ElementTree as ET >>> tree = ET.parse('test.xml') >>> r = tree.getroot() >>> r >>> def trav(node, indent=0): ... for c in node.getchildren(): ... print ' '*indent, c.tag, ':', c.text ... trav(c, indent+1) ... >>> >>> trav(r) header1 : abc text1 : This is some b : text text1 : This is some more text >>> }}} 1. '''SQLite支持增进''' * 追加了`sqlite3`模块{{{ import sqlite3 conn = sqlite3.connect('data.dat') c = conn.cursor() c.execute(''' create table members( id int, name varchar, login timestamp ) ''') c.execute(''' insert into members values (1,'jeff','2006-10-01') ''') c.execute(''' insert into members values (2,'angie','2006-10-02') ''') c.execute(''' insert into members values (3,'dylan','2006-10-03') ''') res = c.execute('select * from members') for row in res: print row }}} ---- [[技术文档分类]]