python2.7和3.0區別

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章