Python3.x和Python2.x的區別


http://www.techug.com/the-difference-of-python2-and-python3#print

===================================================================

這個星期開始學習Python了,因為看的書都是基於Python2.x,而且我安裝的是Python3.1,所以書上寫的地方好多都不適用於Python3.1,特意在Google上search了一下3.x和2.x的區別。特此在自己的空間中記錄一下,以備以后查找方便,也可以分享給想學習Python的friends.

 

1.性能 
Py3.0運行 pystone benchmark的速度比Py2.5慢30%。Guido認為Py3.0有極大的優化空間,在字符串和整形操作上可 
以取得很好的優化結果。 
Py3.1性能比Py2.5慢15%,還有很大的提升空間。 
2.編碼 
Py3.X源碼文件默認使用utf-8編碼,這就使得以下代碼是合法的: 
    >>> 中國 = 'china' 
    >>>print(中國) 
    china 
3. 語法 
1)去除了<>,全部改用!= 
2)去除``,全部改用repr() 
3)關鍵詞加入as 和with,還有True,False,None 
4)整型除法返回浮點數,要得到整型結果,請使用// 
5)加入nonlocal語句。使用noclocal x可以直接指派外圍(非全局)變量 
6)去除print語句,加入print()函數實現相同的功能。同樣的還有 exec語句,已經改為exec()函數 
   例如: 
     2.X: print "The answer is", 2*2 
     3.X: print("The answer is", 2*2) 
     2.X: print x,                              # 使用逗號結尾禁止換行 
     3.X: print(x, end=" ")                     # 使用空格代替換行 
     2.X: print                                 # 輸出新行 
     3.X: print()                               # 輸出新行 
     2.X: print >>sys.stderr, "fatal error" 
     3.X: print("fatal error", file=sys.stderr) 
     2.X: print (x, y)                          # 輸出repr((x, y)) 
     3.X: print((x, y))                         # 不同於print(x, y)! 
7)改變了順序操作符的行為,例如x<y,當x和y類型不匹配時拋出TypeError而不是返回隨即的 bool值  
8)輸入函數改變了,刪除了raw_input,用input代替: 
   2.X:guess = int(raw_input('Enter an integer : ')) # 讀取鍵盤輸入的方法 
   3.X:guess = int(input('Enter an integer : '))

9)去除元組參數解包。不能def(a, (b, c)):pass這樣定義函數了 
10)新式的8進制字變量,相應地修改了oct()函數。 
   2.X的方式如下: 
     >>> 0666 
     438 
     >>> oct(438) 
     '0666' 
   3.X這樣: 
     >>> 0666 
     SyntaxError: invalid token (<pyshell#63>, line 1) 
     >>> 0o666 
     438 
     >>> oct(438) 
     '0o666' 
11)增加了 2進制字面量和bin()函數 
    >>> bin(438) 
    '0b110110110' 
    >>> _438 = '0b110110110' 
    >>> _438 
    '0b110110110' 
12)擴展的可迭代解包。在Py3.X 里,a, b, *rest = seq和 *rest, a = seq都是合法的,只要求兩點:rest是list 
對象和seq是可迭代的。 
13)新的super(),可以不再給super()傳參數, 
    >>> class C(object): 
          def __init__(self, a): 
             print('C', a) 
    >>> class D(C): 
          def __init(self, a): 
             super().__init__(a) # 無參數調用super() 
    >>> D(8) 
    C 8 
    <__main__.D object at 0x00D7ED90> 
14)新的metaclass語法: 
    class Foo(*bases, **kwds): 
      pass 
15)支持class decorator。用法與函數decorator一樣: 
    >>> def foo(cls_a): 
          def print_func(self): 
             print('Hello, world!') 
          cls_a.print = print_func 
          return cls_a 
    >>> @foo 
    class C(object): 
      pass 
    >>> C().print() 
    Hello, world! 
class decorator可以用來玩玩狸貓換太子的大把戲。更多請參閱PEP 3129 
4. 字符串和字節串 
1)現在字符串只有str一種類型,但它跟2.x版本的unicode幾乎一樣。

2)關於字節串,請參閱“數據類型”的第2條目 
5.數據類型 
1)Py3.X去除了long類型,現在只有一種整型——int,但它的行為就像2.X版本的long 
2)新增了bytes類型,對應於2.X版本的八位串,定義一個bytes字面量的方法如下: 
    >>> b = b'china' 
    >>> type(b) 
    <type 'bytes'> 
str對象和bytes對象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互轉化。 
    >>> s = b.decode() 
    >>> s 
    'china' 
    >>> b1 = s.encode() 
    >>> b1 
    b'china' 
3)dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函數都被廢棄。同時去掉的還有 
dict.has_key(),用 in替代它吧 
6.面向對象 
1)引入抽象基類(Abstraact Base Classes,ABCs)。 
2)容器類和迭代器類被ABCs化,所以cellections模塊里的類型比Py2.5多了很多。 
    >>> import collections 
    >>> print('\n'.join(dir(collections))) 
    Callable 
    Container 
    Hashable 
    ItemsView 
    Iterable 
    Iterator 
    KeysView 
    Mapping 
    MappingView 
    MutableMapping 
    MutableSequence 
    MutableSet 
    NamedTuple 
    Sequence 
    Set 
    Sized 
    ValuesView 
    __all__ 
    __builtins__ 
    __doc__ 
    __file__ 
    __name__ 
    _abcoll 
    _itemgetter 
    _sys 
    defaultdict 
    deque 
另外,數值類型也被ABCs化。關於這兩點,請參閱 PEP 3119和PEP 3141。 
3)迭代器的next()方法改名為__next__(),並增加內置函數next(),用以調用迭代器的__next__()方法 
4)增加了@abstractmethod和 @abstractproperty兩個 decorator,編寫抽象方法(屬性)更加方便。 
7.異常 
1)所以異常都從 BaseException繼承,並刪除了StardardError 
2)去除了異常類的序列行為和.message屬性 
3)用 raise Exception(args)代替 raise Exception, args語法 
4)捕獲異常的語法改變,引入了as關鍵字來標識異常實例,在Py2.5中: 
    >>> try: 
    ...    raise NotImplementedError('Error') 
    ... except NotImplementedError, error:

    ...    print error.message 
    ... 
    Error 
在Py3.0中: 
    >>> try: 
          raise NotImplementedError('Error') 
        except NotImplementedError as error: #注意這個 as 
          print(str(error)) 
    Error 
5)異常鏈,因為__context__在3.0a1版本中沒有實現 
8.模塊變動 
1)移除了cPickle模塊,可以使用pickle模塊代替。最終我們將會有一個透明高效的模塊。 
2)移除了imageop模塊 
3)移除了 audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,  
rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模塊 
4)移除了bsddb模塊(單獨發布,可以從http://www.jcea.es/programacion/pybsddb.htm獲取) 
5)移除了new模塊 
6)os.tmpnam()和os.tmpfile()函數被移動到tmpfile模塊下 
7)tokenize模塊現在使用bytes工作。主要的入口點不再是generate_tokens,而是 tokenize.tokenize() 
9.其它 
1)xrange() 改名為range(),要想使用range()獲得一個list,必須顯式調用: 
    >>> list(range(10)) 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
2)bytes對象不能hash,也不支持 b.lower()、b.strip()和b.split()方法,但對於后兩者可以使用 b.strip(b’  
\n\t\r \f’)和b.split(b’ ‘)來達到相同目的 
3)zip()、map()和filter()都返回迭代器。而apply()、 callable()、coerce()、 execfile()、reduce()和reload 
()函數都被去除了

現在可以使用hasattr()來替換 callable(). hasattr()的語法如:hasattr(string, '__name__')

4)string.letters和相關的.lowercase和.uppercase被去除,請改用string.ascii_letters 等 
5)如果x < y的不能比較,拋出TypeError異常。2.x版本是返回偽隨機布爾值的 
6)__getslice__系列成員被廢棄。a[i:j]根據上下文轉換為a.__getitem__(slice(I, j))或 __setitem__和 
__delitem__調用 
7)file類被廢棄,在Py2.5中: 
    >>> file 
    <type 'file'> 
在Py3.X中: 
    >>> file 
    Traceback (most recent call last): 
    File "<pyshell#120>", line 1, in <module> 
       file 
    NameError: name 'file' is not defined

=====================

Python2.4+ 與 Python3.0+ 主要變化或新增內容

Python2                 Python3
print是內置命令           print變為函數
print >> f,x,y          print(x,y,file=f)
print x,                print(x,end='')
reload(M)               imp.reload(M)
apply(f, ps, ks)        f(*ps, **ks)
x <> y                  x != y
long                    int
1234L                   1234
d.has_key(k)            k in d 或 d.get(k) != None (has_key已死, in永生!!)
raw_input()             input()
input()                 eval(input())
xrange(a,b)             range(a,b)
file()                  open()
x.next()                x.__next__() 且由next()方法調用
x.__getslice__()        x.__getitem__()
x.__setsilce__()        x.__setitem__()
__cmp__()               刪除了__cmp__(),改用__lt__(),__gt__(),__eq__()等
reduce()                functools.reduce()
exefile(filename)       exec(open(filename).read())
0567                    0o567 (八進制)
                        新增nonlocal關鍵字
                        str用於Unicode文本,bytes用於二進制文本
                        新的迭代器方法range,map,zip等
                        新增集合解析與字典解析
u'unicodestr'           'unicodestr'
raise E,V               raise E(V)
except E , x:           except E as x:
file.xreadlines         for line in file: (or X = iter(file))
d.keys(),d.items(),etc  list(d.keys()),list(d.items()),list(etc)
map(),zip(),etc         list(map()),list(zip()),list(etc)
x=d.keys(); x.sort()    sorted(d)
x.__nonzero__()         x.__bool__()
x.__hex__,x.__bin__     x.__index__
types.ListType          list
__metaclass__ = M       class C(metaclass = M):
__builtin__             builtins
sys.exc_type,etc        sys.exc_info()[0],sys.exc_info()[1],...
function.func_code      function.__code__
                        增加Keyword-One參數
                        增加Ellipse對象
                        簡化了super()方法語法
用過-t,-tt控制縮進        混用空格與制表符視為錯誤
from M import *可以      只能出現在文件的頂層
出現在任何位置.
class MyException:      class MyException(Exception):
thread,Queue模塊         改名_thread,queue
cPickle,SocketServer模塊 改名_pickle,socketserver
ConfigSparser模塊        改名configsparser
Tkinter模塊              改名tkinter
                        其他模塊整合到了如http模塊,urllib, urllib2模塊等
os.popen                subprocess.Popen
基於字符串的異常           基於類的異常
                        新增類的property機制(類特性)
未綁定方法                都是函數
混合類型可比較排序         非數字混合類型比較發生錯誤
/是傳統除法               取消了傳統除法, /變為真除法
無函數注解                有函數注解 def f(a:100, b:str)->int 使用通過f.__annotation__
                        新增環境管理器with/as
                        Python3.1支持多個環境管理器項 with A() as a, B() as b
                        擴展的序列解包 a, *b = seq
                        統一所有類為新式類
                        增強__slot__類屬性
if X: 優先X.__len__()    優先X.__bool__()
type(I)區分類和類型       不再區分(不再區分新式類與經典類,同時擴展了元類)
靜態方法需要self參數       靜態方法根據聲明直接使用
無異常鏈                  有異常鏈 raise exception from other_exception

=================================================================
 
http://chenqx.github.io/2014/11/10/Key-differences-between-Python-2-7-x-and-Python-3-x/
 

因這學期負責Python課程的助教,剛開始上機試驗的幾節課,有很多同學用 Python3.4 的編譯器編譯 Python 2.7 的程序而導致不通過。Python 2.7.x 和 Python 3.x 版本並非完全兼容。
  許多 Python 初學者想知道他們應該從 Python 的哪個版本開始學習。對於這個問題我的答案是 “你學習你喜歡的教程的版本,然后檢查他們之間的不同。” 但如果你並未了解過兩個版本之間的差異,個人推薦使用 Python 2.7.x 版本,畢竟大部分教材等資料還是用Python 2.7.x來寫的。
  但是如果你開始一個新項目,並且有選擇權?我想說的是目前沒有對錯,只要你計划使用的庫 Python 2.7.x 和 Python 3.x 雙方都支持的話。盡管如此,當在編寫它們中的任何一個的代碼,或者是你計划移植你的項目的時候,是非常值得看看這兩個主要流行的 Python 版本之間的差別的,以便避免常見的陷阱。
  本文翻譯自:《Key differences between Python 2.7.x and Python 3.x》

__future__模塊

  Python 3.x 介紹的 一些Python 2 不兼容的關鍵字和特性可以通過在 Python 2 的內置 __future__ 模塊導入。如果你計划讓你的代碼支持 Python 3.x,建議你使用 __future__ 模塊導入。例如,如果我想要 在Python 2 中表現 Python 3.x 中的整除,我們可以通過如下導入

1
from __future__ import division

  更多的 __future__ 模塊可被導入的特性被列在下表中:

feature optional in mandatory in effect
nested_scopes 2.1.0b1 2.2 PEP 227: Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255: Simple Generators
division 2.2.0a2 3.0 PEP 238: Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343: The “with” Statement
print_function 2.5.0a2 3.0 PEP 3105: Make print a function
unicode_literals 2.5.0a2 3.0 PEP 3112: Bytes literals in Python 3000

(Source: https://docs.python.org/2/library/future.html)

1
from platform import python_version

print函數

  很瑣碎,而 print 語法的變化可能是最廣為人知的了,但是仍值得一提的是: Python 2 的 print 聲明已經被 print() 函數取代了,這意味着我們必須包裝我們想打印在小括號中的對象。
Python 2 不具有額外的小括號問題。但對比一下,如果我們按照 Python 2 的方式不使用小括號調用 print 函數,Python 3 將拋出一個語法異常(SyntaxError)。

Python 2

1
2
3
4
print 'Python', python_version()
print 'Hello, World!'
print( 'Hello, World!')
print "text", ; print 'print more text on the same line'

run result:
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

1
2
3
4
print( 'Python', python_version())
print( 'Hello, World!')
print( "some text,", end="")
print( ' print more text on the same line')

run result:
Python 3.4.1
Hello, World!
some text, print more text on the same line

1
print 'Hello, World!'

run result:
File ““, line 1
  print ‘Hello, World!’
          ^
SyntaxError: invalid syntax

Note:
  以上通過 Python 2 使用 Printing "Hello, World" 是非常正常的,盡管如此,如果你有多個對象在小括號中,我們將創建一個元組,因為 print在 Python 2 中是一個聲明,而不是一個函數調用。

1
2
3
print 'Python', python_version()
print( 'a', 'b')
print 'a', 'b'

run result:
Python 2.7.7
(‘a’, ‘b’)
a b

整除

  如果你正在移植代碼,這個變化是特別危險的。或者你在 Python 2 上執行 Python 3 的代碼。因為這個整除的變化表現在它會被忽視(即它不會拋出語法異常)。
  因此,我還是傾向於使用一個 float(3)/2 或 3/2.0 代替在我的 Python 3 腳本保存在 Python 2 中的 3/2 的一些麻煩(並且反而過來也一樣,我建議在你的 Python 2 腳本中使用 from __future__ import division
  
Python 2

1
2
3
4
5
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

run result:
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

1
2
3
4
5
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)

run result:
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) 字符串,以及一個字節類:byte 和 bytearrays

Python 2

1
print 'Python', python_version()

run result:
Python 2.7.6

1
print type(unicode('this is like a python3 str type'))

run result:
< type ‘unicode’ >

1
print type(b'byte type does not exist')

run result:
< type ‘str’ >

1
print 'they are really' + b' the same'

run result:
they are really the same

1
print type(bytearray(b'bytearray oddly does exist though'))

run result:
< type ‘bytearray’ >

Python 3

1
2
print( 'Python', python_version())
print( 'strings are now utf-8 \u03BCnico\u0394é!')

run result:
Python 3.4.1
strings are now utf-8 μnicoΔé!

1
2
print( 'Python', python_version(), end="")
print( ' has', type(b' bytes for storing data'))

run result:
Python 3.4.1 has < class ‘bytes’ >

1
2
print( 'and Python', python_version(), end="")
print( ' also has', type(bytearray(b'bytearrays')))

run result:
and Python 3.4.1 also has < class ‘bytearray’>

1
'note that we cannot add a string' + b'bytes for data'

run result:
-—————————————————————————————————————
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 中 xrange() 創建迭代對象的用法是非常流行的。比如: for 循環或者是列表/集合/字典推導式。
  這個表現十分像生成器(比如。“惰性求值”)。但是這個 xrange-iterable 是無窮的,意味着你可以無限遍歷。
  由於它的惰性求值,如果你不得僅僅不遍歷它一次,xrange() 函數 比 range() 更快(比如 for 循環)。盡管如此,對比迭代一次,不建議你重復迭代多次,因為生成器每次都從頭開始。
  在 Python 3 中,range() 是像 xrange() 那樣實現以至於一個專門的 xrange() 函數都不再存在(在 Python 3 中 xrange() 會拋出命名異常)。

1
2
3
4
5
6
7
8
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

1
2
3
4
5
print 'Python', python_version()
print '\ntiming range()'
%timeit test_range(n)
print '\n\ntiming xrange()'
%timeit test_xrange(n)

run result:
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

1
2
3
print( 'Python', python_version())
print( '\ntiming range()')
%timeit test_range(n)

run result:
Python 3.4.1

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

1
print(xrange( 10))

run result:
-—————————————————————————————————————
NameError Traceback (most recent call last)

in ()
——> 1 print(xrange(10))

NameError: name ‘xrange’ is not defined

Python3中的range對象的__contains__方法

  另外一件值得一提的事情就是在 Python 3 中 range 有一個新的 __contains__ 方法(感謝 Yuchen Ying 指出了這個),__contains__ 方法可以加速 “查找” 在 Python 3.x 中顯著的整數和布爾類型。

1
2
3
4
5
6
7
8
9
10
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)

run result:
Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop
  
  基於以上的 timeit 的結果,當它使一個整數類型,而不是浮點類型的時候,你可以看到執行查找的速度是 60000 倍快。盡管如此,因為 Python 2.x 的 range 或者是 xrange 沒有一個 __contains__ 方法,這個整數類型或者是浮點類型的查詢速度不會相差太大。

1
2
3
4
5
6
7
8
9
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)

run result:
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 中的證據:

1
2
print( 'Python', python_version())
range.__contains__

run result:
Python 3.4.1

< slot wrapper ‘contains‘ of ‘range’ objects >

1
2
print 'Python', python_version()
range.__contains__

run result:
Python 2.7.7

-—————————————————————————————————————
AttributeError Traceback (most recent call last)
< ipython-input-7-05327350dafb> in < module>()
1 print ‘Python’, pythonversion()
——> 2 range.`_contains
`

AttributeError: ‘builtinfunctionor_method’ object has no attribute `’__contains‘`

1
2
print 'Python', python_version()
xrange.__contains__

run result:
Python 2.7.7

-—————————————————————————————————————
AttributeError Traceback (most recent call last)
< ipython-input-8-7d1a71bfee8e> in < module>()
1 print ‘Python’, pythonversion()
——> 2 xrange.`_contains
`

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

  注意在 Python 2 和 Python 3 中速度的不同
  有些人指出了 Python 3 的 range() 和 Python 2 的 xrange() 之間的速度不同。因為他們是用相同的方法實現的,因此期望相同的速度。盡管如此,這事實在於 Python 3 傾向於比 Python 2 運行的慢一點。

1
2
3
4
5
def test_while():
i = 0
while i < 20000:
i += 1
return

Python 3

1
2
print( 'Python', python_version())
%timeit test_while()

run result:
Python 3.4.1
100 loops, best of 3: 2.68 ms per loop

Python 2

1
2
print 'Python', python_version()
%timeit test_while()

run result:
Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

Raising exceptions

  Python 2 接受新舊兩種語法標記,在 Python 3 中如果我不用小括號把異常參數括起來就會阻塞(並且反過來引發一個語法異常)。

Python 2

1
print 'Python', python_version()

run result:
Python 2.7.6

1
raise IOError, "file error"

run result:

-—————————————————————————————————————
IOError Traceback (most recent call last)
< ipython-input-8-25f049caebb0> in < module>()
——> 1 raise IOError, “file error”

IOError: file error

1
raise IOError("file error")

run result:
-—————————————————————————————————————
IOError Traceback (most recent call last)
< ipython-input-9-6f1c43f525b2> in < module>()
——> 1 raise IOError(“file error”)

IOError: file error

Python 3

1
print 'Python', python_version()

run result:
Python 3.4.1

1
raise IOError, "file error"

run result:

File ““, line 1
raise IOError, “file error”
      ^
SyntaxError: invalid syntax
  
  在 Python 3 中,可以這樣拋出異常:

1
2
print( 'Python', python_version())
raise IOError("file error")

run result:
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

Handling exceptions

  在 Python 3 中處理異常也輕微的改變了,在 Python 3 中我們現在使用 as 作為關鍵詞。

Python 2

1
2
3
4
5
print 'Python', python_version()
try:
let_us_cause_a_NameError
except NameError, err:
print err, '--> our error message'

run result:
Python 2.7.6
name ‘let_us_cause_a_NameError’ is not defined —> our error message

Python 3

1
2
3
4
5
print( 'Python', python_version())
try:
let_us_cause_a_NameError
except NameError as err:
print(err, '--> our error message')

run result:

Python 3.4.1
name ‘let_us_cause_a_NameError’ is not defined —> our error message

next()函數 and .next()方法

  因為 next() (.next()) 是一個如此普通的使用函數(方法),這里有另外一個語法改變(或者是實現上改變了),值得一提的是:在 Python 2.7.5 中函數和方法你都可以使用,next() 函數在 Python 3 中一直保留着(調用 .next() 拋出屬性異常)。

Python 2

1
2
3
4
print 'Python', python_version()
my_generator = (letter for letter in 'abcdefg')
next(my_generator)
my_generator.next()

run result:
Python 2.7.6

‘b

Python 3

1
2
3
print( 'Python', python_version())
my_generator = (letter for letter in 'abcdefg')
next(my_generator)

run result:
Python 3.4.1

‘a’

1
my_generator.next()

run result:
-—————————————————————————————————————
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 中有如下描述:
  “列表推導不再支持 [... for var in item1, item2, ...] 這樣的語法。使用 [... for var in (item1, item2, ...)] 代替。也需要提醒的是列表推導有不同的語義: 他們關閉了在 list() 構造器中的生成器表達式的語法糖, 並且特別是循環控制變量不再泄漏進周圍的作用范圍域.”

Python 2

1
2
3
4
5
print 'Python', python_version()
i = 1
print 'before: i =', i
print 'comprehension: ', [i for i in range(5)]
print 'after: i =', i

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

Python 3

1
2
3
4
5
print( 'Python', python_version())
i = 1
print( 'before: i =', i)
print( 'comprehension:', [i for i in range(5)])
print( 'after: i =', i)

run result:
Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

比較不可排序類型

  在 Python 3 中的另外一個變化就是當對不可排序類型做比較的時候,會拋出一個類型錯誤。

Python 2

1
2
3
4
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)

run result:
Python 2.7.6
[1, 2] > ‘foo’ = False
(1, 2) > ‘foo’ = True
[1, 2] > (1, 2) = False

Python 3

1
2
3
4
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))

run result:
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()解析用戶的輸入

  幸運的是,在 Python 3 中已經解決了把用戶的輸入存儲為一個 str 對象的問題。為了避免在 Python 2 中的讀取非字符串類型的危險行為,我們不得不使用 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() 函數簡單的把迭代對象轉換成一個列表。

Python 2

1
2
3
print 'Python', python_version()
print range(3)
print type(range(3))

run result:
Python 2.7.6
[0, 1, 2]
< type ‘list’>

Python 3

1
2
3
4
print( 'Python', python_version())
print(range( 3))
print(type(range( 3)))
print(list(range( 3)))

run result:
Python 3.4.1
range(0, 3)
< class ‘range’>
[0, 1, 2]
  
  在 Python 3 中一些經常使用到的不再返回列表的函數和方法:

  • zip()
  • map()
  • filter()
  • dictionary’s .keys() method
  • dictionary’s .values() method
  • dictionary’s .items() method

更多的關於 Python 2 和 Python 3 的文章

  下面是我建議后續的關於 Python 2 和 Python 3 的一些好文章。

移植到 Python 3

Python 3 的擁護者和反對者


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM