文档翻译 Python 2.7.x和Python 3.x之间的主要区别(包括示例)

许多Python初学者都想知道应该从哪一个版本的Python开始。我对这个问题的回答一般是“仅需使用您喜欢的教程所写的版本,并在之后查看差别”。html

可是,若是您开始一个新项目并能够选择,该怎么办?我要说的是,只要Python 2.7.x和Python 3.x都支持您计划使用的库,那么目前就没有“对”或“错”。可是,这两个最受欢迎的Python版本之间的主要区别值得一看,以此避免在为其中任何一个编写代码或计划移植项目时碰见陷阱。python

 

__future__模块

Python 3.x引入了一些Python 2不兼容的关键字和功能,能够经过__future__Python 2 的内置模块导入这些关键字和功能。__future__若是您打算为代码提供Python 3.x支持,建议使用import导入。例如,若是咱们想要Python 2中Python 3.x的整数除法行为,则能够经过如下方式将其导入git

from __future__ import division

__future__下表列出了能够从模块导入的更多功能:github

特征 可选(版本) 强制(版本) 影响
nested_scopes 2.1.0b1 2.2 PEP 227静态嵌套的合并范围
generators 2.2.0a1 2.3 PEP 255简单生成器
division 2.2.0a2 3.0 PEP 238更改除法运算符
absolute_import 2.5.0a1 3.0 PEP 328导入:多行和绝对/相对
with_statement 2.5.0a1 2.6 PEP 343“ with”声明
print_function 2.6.0a2 3.0 PEP 3105使打印功能
unicode_literals 2.6.0a2 3.0 PEP 3112Python 3000中的字节字面量

(来源:[https://docs.python.org/2/library/__future__.html](https://docs.python.org/2/library/__future__.html#module-__future__))算法

from platform import python_version

打印功能

很是琐碎,而且print语法中的更改多是最广为人知的更改,但仍然值得一提:Python 2的print语句已被该print()函数替换,这意味着咱们必须把要打印的对象包装在括号中。app

若是咱们用Python 2的不带括号的方式调用print功能, Python 2不会出现其余额外问题,可是相反,Python 3会抛出一个SyntaxError函数

Python 2

print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print('Python', python_version())
print('Hello, World!')

print("some text,", end="")
print(' print more text on the same line')
Python 3.4.1
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
File "<ipython-input-3-139a7c5835bd>", line 1
  print 'Hello, World!'
                      ^
SyntaxError: invalid syntax

注意:oop

经过Python 2在上面打印“ Hello,World”看起来很“正常”。可是,若是在括号内有多个对象,则将建立一个元组,由于这个print在Python 2中是“语句”,而不是函数调用。ui

print 'Python', python_version()
print('a', 'b')
print 'a', 'b'
Python 2.7.7
('a', 'b')
a b

整数除法

若是您正在移植代码,或者您正在Python 2中执行Python 3代码,则此更改特别危险,由于整数除法行为的更改一般不会引发注意(它不会引起SyntaxError)。 所以,我仍然倾向于在个人Python 3脚本中使用float(3)/23/2.0代替a 3/2,以避免给Python 2带来麻烦(反之亦然,我建议在您的Python 2脚本中使用from __future__ import division )。this

Python 2

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Unicode

Python 2具备ASCII str()类型,独有类型unicode(),但没有byte类型。

如今,在Python 3中,咱们终于有了Unicode(utf-8)strings和2个字节的类:bytebytearray

Python 2

print 'Python', python_version()
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

print('Python', python_version())
print('strings are now utf-8 \u03BCnico\u0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
'note that we cannot add a string' + b'bytes for data'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-13-d3e8942ccf81> in <module>()
----> 1 'note that we cannot add a string' + b'bytes for data'


TypeError: Can't convert 'bytes' object to str implicitly

Xrange

在Python 2.x中,用xrange()在建立可迭代对象很是流行(例如在for循环或list / set-dictionary-comprehension 中)。 该行为与生成器很是类似(即“惰性求值”),可是这里的xrange-iterable不是穷举的--这意味着,您能够对其进行无限迭代。

因为其“惰性求值”,range()的常规优点在于,若是您只须要对其进行一次迭代(例如,在for循环中),一般xrange()更快。可是,与一次迭代相反,这里不建议重复屡次,由于每次生成都是从头开始的!

在Python 3中,range()的实现相似于xrange()函数,所以xrange()再也不是专有函数(在Python 3中xrange()引起了NameError)。

import timeit

n = 10000
def test_range(n):
  return for i in range(n):
      pass

def test_xrange(n):
  for i in xrange(n):
      pass    

Python 2

print 'Python', python_version()

print '\ntiming range()'
%timeit test_range(n)

print '\n\ntiming xrange()'
%timeit test_xrange(n)
Python 2.7.6

timing range()
1000 loops, best of 3: 433 µs per loop


timing xrange()
1000 loops, best of 3: 350 µs per loop

Python 3

print('Python', python_version())

print('\ntiming range()')
%timeit test_range(n)
Python 3.4.1

timing range()
1000 loops, best of 3: 520 µs per loop
print(xrange(10))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

<ipython-input-5-5d8f9b79ea70> in <module>()
----> 1 print(xrange(10))


NameError: name 'xrange' is not defined

 

Python 3中range对象的__contains__方法

值得一提的另外一件事是在Python 3.x 中range有了一个“新” __contains__方法(感谢Yuchen Ying指出了这一点)。对于整数和布尔类型,该__contains__方法能够大大加快Python 3.x中range的“查找”速度。

x = 10000000
def val_in_range(x, val):
  return val in range(x)
def val_in_xrange(x, val):
  return val in xrange(x)
print('Python', python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)
Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop

根据上面的timeit结果,您能够看到当“查找”的执行对象是整数类型而不是浮点型时,执行速度提升了约60,000。可是,因为Python 2.x rangexrange没有__contains__方法,整数或浮点数的“查找速度”不会有太大不一样:

print 'Python', python_version()
assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)
Python 2.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop

在该__contain__方法还没有添加到Python 2.x 的“proofs”之下:

print('Python', python_version())
range.__contains__
Python 3.4.1





<slot wrapper '__contains__' of 'range' objects>
print 'Python', python_version()
range.__contains__
Python 2.7.7



---------------------------------------------------------------------------
AttributeError                           Traceback (most recent call last)

<ipython-input-7-05327350dafb> in <module>()
    1 print 'Python', python_version()
----> 2 range.__contains__


AttributeError: 'builtin_function_or_method' object has no attribute '__contains__'
print 'Python', python_version()
xrange.__contains__
Python 2.7.7



---------------------------------------------------------------------------
AttributeError                           Traceback (most recent call last)

<ipython-input-8-7d1a71bfee8e> in <module>()
    1 print 'Python', python_version()
----> 2 xrange.__contains__


AttributeError: type object 'xrange' has no attribute '__contains__'

注意Python 2和3中的速度差别

有人指出Python 3 range()和Python2 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
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

在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中能够同时使用函数和方法,该next()函数就是仍保留在Python 3中(调用.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中所作的更改,并在Python 3.0的新增功能中进行了以下描述:

 

"列表理解再也不支持语法形式[... for var in item1, item2, ...]。使用[... for var in (item1, item2, ...)]代替。还要注意,列表理解具备不一样的语义:对于list()构造函数内部的生成器表达式,它们更接近语法糖,而且尤为是循环控制变量再也不泄漏到周围的范围中。"

Python 2

print 'Python', python_version()

i = 1
print 'before: i =', i

print 'comprehension: ', [i for i in range(5)]

print 'after: i =', i
Python 2.7.6
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 4

Python 3

print('Python', python_version())

i = 1
print('before: i =', i)

print('comprehension:', [i for i in range(5)])

print('after: i =', i)
Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

比较无序类型

Python 3的另外一个不错的变化是,若是咱们尝试比较无序类型,则会引起TypeError警告。

Python 2

print 'Python', python_version()
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)
Python 2.7.6
[1, 2] > 'foo' = False
(1, 2) > 'foo' = True
[1, 2] > (1, 2) = False

Python 3

print('Python', python_version())
print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
Python 3.4.1



---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-16-a9031729f4a0> in <module>()
    1 print('Python', python_version())
----> 2 print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
    3 print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
    4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))


TypeError: unorderable types: list() > str()

 

经过input()解析用户输入

幸运的是,该input()函数已在Python 3中修复,所以它始终将用户输入存储为str对象。为了不在Python 2中使用strings之外的其余类型进行读取的危险行为,咱们必须改变raw_input()的使用。

Python 2

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'int'>

>>> my_input = raw_input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'str'>

Python 3

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<class 'str'>

返回可迭代对象而不是列表

如本xrange节所述,一些函数和方法如今在Python 3中返回可迭代对象-而不是Python 2中的列表。

因为咱们一般只迭代一次,所以我认为这种更改在节省内存方面颇有意义。可是,与生成器相比,若是须要的话,也有可能迭代屡次,至于此这并非那么有效。

对于那些咱们确实须要list-objects的状况,咱们能够简单的经过list()函数将可迭代对象转换为list

Python 2

print 'Python', python_version()

print range(3)
print type(range(3))
Python 2.7.6
[0, 1, 2]
<type 'list'>

Python 3

print('Python', python_version())

print(range(3))
print(type(range(3)))
print(list(range(3)))
Python 3.4.1
range(0, 3)
<class 'range'>
[0, 1, 2]

Python 3中一些再也不返回列表的更经常使用的函数和方法:

  • zip()

  • map()

  • filter()

  • 字典的.keys()方法

  • 字典的.values()方法

  • 字典的.items()方法

银行家算法(四舍六入五成双:译者按)

当Python 3在最后一个有效数字处产生并列(.5)时,Python 3采用了如今的四舍五入方式。如今,在Python 3中,小数点将四舍五入为最接近的偶数。尽管这对于代码可移植性带来了不便,可是与四舍五入相比,它被认为是一种更好的舍入方式,由于它避免了偏向大数的状况。有关更多信息,请参见优秀的的Wikipedia文章和段落:

Python 2

print 'Python', python_version()
Python 2.7.12
round(15.5)
16.0
round(16.5)
17.0

Python 3

print('Python', python_version())
Python 3.5.1
round(15.5)
16
round(16.5)
16

 

 

原文连接:  https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#more-articles-about-python-2-and-python-3

做者:塞巴斯蒂安·拉施卡(Sebastian Raschka)

翻译:  墨寒

相关文章
相关标签/搜索