Python 2.7.x 和 3.x 版本的重要区别小结(4)
有读者指出了Python 3中的range()和Python 2中xrange()执行速度有差异。由于这两者的实现方式相同,因此理论上执行速度应该也是相同的。这里的速度差别仅仅是因为Python 3的总体速度就比Python 2慢。
def test_while(): i = 0 while i < 20000: i += 1 return
print('Python', python_version()) %timeit test_while()
Python 3.4.1 %timeit test_while() 100 loops, best of 3: 2.68 ms per loop
print 'Python', python_version() %timeit test_while()
Python 2.7.6 1000 loops, best of 3: 1.72 ms per loop
触发异常
[回到目录]
Python 2支持新旧两种异常触发语法,而Python 3只接受带括号的的语法(不然会触发SyntaxError):
Python 2
print 'Python', python_version()
Python 2.7.6
raise IOError, "file error"
--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-8-25f049caebb0> in <module>() ----> 1 raise IOError, "file error" IOError: file error
raise IOError("file error")
--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-9-6f1c43f525b2> in <module>() ----> 1 raise IOError("file error") IOError: file error
Python 3
print('Python', python_version())
Python 3.4.1
raise IOError, "file error"
File "<ipython-input-10-25f049caebb0>", line 1 raise IOError, "file error" ^ SyntaxError: invalid syntax The proper way to raise an exception in Python 3:
print('Python', python_version()) raise IOError("file error")
Python 3.4.1 --------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-11-c350544d15da> in <module>() 1 print('Python', python_version()) ----> 2 raise IOError("file error") OSError: file error
异常处理
[回到目录]
Python 3中的异常处理也发生了一点变化。在Python 3中必须使用“as”关键字。
Python 2
print 'Python', python_version() try: let_us_cause_a_NameError except NameError, err: print err, '--> our error message'
Python 2.7.6 name 'let_us_cause_a_NameError' is not defined --> our error message
Python 3
print('Python', python_version()) try: let_us_cause_a_NameError except NameError as err: print(err, '--> our error message')
Python 3.4.1 name 'let_us_cause_a_NameError' is not defined --> our error message
next()函数和.next()方法
[回到目录]
由于会经常用到next()(.next())函数(方法),所以还要提到另一个语法改动(实现方面也做了改动):在Python 2.7.5中,函数形式和方法形式都可以使用,而在Python 3中,只能使用next()函数(试图调用.next()方法会触发AttributeError)。
Python 2
print 'Python', python_version() my_generator = (letter for letter in 'abcdefg') next(my_generator) my_generator.next()
Python 2.7.6 'b'
Python 3
print('Python', python_version()) my_generator = (letter for letter in 'abcdefg') next(my_generator)
Python 3.4.1 'a'
my_generator.next()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-14-125f388bb61b> in <module>() ----> 1 my_generator.next() AttributeError: 'generator' object has no attribute 'next'
For循环变量与全局命名空间泄漏
[回到目录]
好消息是:在Python 3.x中,for循环中的变量不再会泄漏到全局命名空间中了!
这是Python 3.x中做的一个改动,在“What's New In Python 3.0”中有如下描述: