python3和python2的區別

2021-08-11 08:09:34 字數 2944 閱讀 8720

**:

這個星期開始學習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. 語法

9)去除元組引數解包。不能def(a, (b, c)):pass這樣定義函式了 

10)新式的8進製字變數,相應地修改了oct()函式。 

2.x的方式如下: 

>>> 0666 

438 

>>> oct(438) 

'0666' 

3.x這樣: 

>>> 0666 

syntaxerror: invalid token (, 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)所以異常都從 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.模組變動

現在可以使用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 

在py3.x中: 

>>> file 

traceback (most recent call last): 

file "", line 1, in

file 

nameerror: name 'file' is not defined

python3和python2的區別

1.效能 py3.0執行 pystone benchmark的速度比py2.5慢30 guido認為py3.0有極大的優化空間,在字串和整形操作上可 以取得很好的優化結果。py3.1效能比py2.5慢15 還有很大的提公升空間。2.編碼 py3.x原始碼檔案預設使用utf 8編碼,這就使得以下 是合...

Python2和Python3的比較

python2 python3 print fish print fish unicode 是單獨的 unicode utf 8 字串 b b china byte 和 bytearrays type b type bytes s b.decode 轉化成 string 型別b1 s encode ...

Python2和Python3的區別

1.輸入輸出函式 1 print python2 中print是乙個語句,後直接跟要列印的內容 print hello world hello world python3 中的print是乙個函式,被列印內容應作為引數傳入 print hello world hello world 2 輸入函式 p...