Python3 x和Python2 x的區別

2021-07-26 15:52:30 字數 3060 閱讀 7461

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

Python 內建函式(Python 3 x)

1 type obj 返回變數型別 2 isinstance object,class or type or tuple 測試物件是否為指定型別的例項 4 range start,end step 返回乙個 start,end 內的 range 物件,start 預設為 0,step 預設為 1 5...

Python3 x和Python2 x的區別

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

Python3 x和Python2 x的區別

最近在學習使用python3.2,因為目前大多數資料和書籍都是基於python 2.x的,所以在學習的過程中會碰到一些問題,特此記錄,方便查詢不同,並分享給其他需要的朋友。1.效能 py3.0執行 pystone benchmark的速度比py2.5慢30 guido認為py3.0有極大的優化空間,...