python3.0與python2.x的區別

來源:互聯網
上載者:User

 

 

python3.0與python2.x的區別

 

1.效能

Py3.0運行pystone benchmark的速度比Py2.5慢30%。Guido認為Py3.0有極大的最佳化空間,在字串和整形操作上可以取得很好的最佳化結果。

2.編碼

Py3.0源碼檔案預設使用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()函數

1 print語句被print()函數取代了,可以使用關鍵字參數來替代老的print特殊文法。例如:
Old: print "The answer is", 2*2

2 New: print("The answer is", 2*2)

3 Old: print x,                                       # 使用逗號結尾禁止換行

4 New: print(x, end=" ")                      # 使用空格代替換行

5 Old: print                                          # 輸出新行

6 New: print()                                     # 輸出新行

7 Old: print >>sys.stderr, "fatal error"

8 New: print("fatal error", file=sys.stderr)

9 Old: print (x, y)                                # 輸出repr((x, y))

10 New: print((x, y))                            # 不同於print(x, y)!

 

 

7)改變了順序操作符的行為,例如x<y,當x和y類型不符時拋出TypeError而不是返回隨即的bool值


8)輸入函數改變了:

Old:
guess = int(raw_input('Enter an integer : ')) #讀取鍵盤輸入的方法
New:
guess = int(input('Enter an integer : '))

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

10)新式的8進位字變數,相應地修改了oct()函數。2.x的方式如下:

>>> 0666

438

>>> oct(438)

'0666'

3.0這樣:

>>> 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.0裡,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可以用來玩玩狸貓換太子的大把戲。


字串和位元組串

1)現在字串只有str一種類型,但它跟2.x版本的unicode幾乎一樣。

2)關於位元組串,請參閱“資料類型”的第2條目

資料類型

1)Py3.0去除了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替代它吧

物件導向

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,編寫抽象方法(屬性)更加方便。

異常

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版本中還沒有實現,這方面就不說了

 

模組變動

· 移除了cPickle模組,可以使用pickle模組代替。最終我們將會有一個透明高效的模組。

· 移除了imageop模組

· 移除了audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2, rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模組

· 移除了bsddb模組(單獨發布,可以從http://www.jcea.es/programacion/pybsddb.htm擷取)

· 移除了new模組

· os.tmpnam()和os.tmpfile()函數被移動到tmpfile模組下

· tokenize模組現在使用bytes工作。主要的進入點不再是generate_tokens,而是tokenize.tokenize()

 

其它

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()函數都被去除了

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.0中:

>>> file

Traceback (most recent call last):

File "<pyshell#120>", line 1, in <module>

    file

NameError: name 'file' is not defined


 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.