Python2和Python3的區(qū)別

1.性能

Py3.0運(yùn)行 pystone benchmark的速度比Py2.5慢30%。Guido認(rèn)為Py3.0有極大的優(yōu)化空間,在字符串和整形操作上可以取得很好的優(yōu)化結(jié)果。
Py3.1性能比Py2.5慢15%,還有很大的提升空間。

2.編碼

Py3.X源碼文件默認(rèn)使用utf-8編碼,這就使得以下代碼是合法的:

    >>> 中國 = 'china' 
    >>>print(中國) 
    china

3. 語法

  • 去除了<>,全部改用!=
  • 去除``,全部改用 repr()
  • 關(guān)鍵詞加入aswith,還有True,False,None
  • 整型除法返回浮點(diǎn)數(shù),要得到整型結(jié)果,請使用//
  • 加入nonlocal語句。使用noclocal x可以直接指派外圍(非全局)變量
  • 去除print語句,加入print()函數(shù)實(shí)現(xiàn)相同的功能。同樣的還有 exec語句,已經(jīng)改為exec()函數(shù)
    例如:
    2.X: print "The answer is", 2*2 
    3.X: print("The answer is", 2*2) 
    2.X: print x,                              # 使用逗號結(jié)尾禁止換行 
    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)!
  • 改變了順序操作符的行為,例如x<y,當(dāng)x和y類型不匹配時(shí)拋出TypeError而不是返回隨即的 bool
  • 輸入函數(shù)改變了,刪除了raw_input,用input代替:
   2.X:guess = int(raw_input('Enter an integer : ')) # 讀取鍵盤輸入的方法 
   3.X:guess = int(input('Enter an integer : '))
  • 去除元組參數(shù)解包。不能def(a, (b, c)):pass這樣定義函數(shù)了
  • 新式的8進(jìn)制字變量,相應(yīng)地修改了oct()函數(shù)。
   2.X的方式如下: 
     >>> 0666 
     438 
     >>> oct(438) 
     '0666' 
   3.X這樣: 
     >>> 0666 
     SyntaxError: invalid token (<pyshell#63>, line 1) 
     >>> 0o666 
     438 
     >>> oct(438) 
     '0o666'
  • 增加了 2進(jìn)制字面量和bin()函數(shù)
    >>> bin(438) 
    '0b110110110' 
    >>> _438 = '0b110110110' 
    >>> _438 
    '0b110110110' 
  • 擴(kuò)展的可迭代解包。在Py3.X 里,a, b, *rest = seq*rest, a = seq都是合法的,只要求兩點(diǎn):rest是list
    對象和seq是可迭代的。
  • 新的super(),可以不再給super()傳參數(shù),
    >>> class C(object): 
          def __init__(self, a): 
             print('C', a) 
    >>> class D(C): 
          def __init(self, a): 
             super().__init__(a) # 無參數(shù)調(diào)用super() 
    >>> D(8) 
    C 8 
    <__main__.D object at 0x00D7ED90> 
  • 新的metaclass語法:
    class Foo(*bases, **kwds): 
      pass 
  • 支持class decorator。用法與函數(shù)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! 

四、字符串和字節(jié)串

  • 現(xiàn)在字符串只有str一種類型,但它跟2.x版本的unicode幾乎一樣。
  • 關(guān)于字節(jié)串,請參閱“數(shù)據(jù)類型”的第2條目

五、數(shù)據(jù)類型

  • Py3.X去除了long類型,現(xiàn)在只有一種整型——int,但它的行為就像2.X版本的long
  • 新增了bytes類型,對應(yīng)于2.X版本的八位串,定義一個(gè)bytes字面量的方法如下:
    >>> b = b'china' 
    >>> type(b) 
    <type 'bytes'> 
str對象和bytes對象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互轉(zhuǎn)化。 
    >>> s = b.decode() 
    >>> s 
    'china' 
    >>> b1 = s.encode() 
    >>> b1 
    b'china'
  • dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函數(shù)都被廢棄。同時(shí)去掉的還有
    dict.has_key(),用 in替代它

六.面向?qū)ο?/h3>

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 
  • 迭代器的next()方法改名為__next__(),并增加內(nèi)置函數(shù)next(),用以調(diào)用迭代器的__next__()方法
  • 增加了@abstractmethod@abstractproperty兩個(gè) decorator,編寫抽象方法(屬性)更加方便。

七.異常

  1. 所以異常都從 BaseException繼承,并刪除了StardardError
  2. 去除了異常類的序列行為和.message屬性
  3. raise Exception(args)代替 raise Exception, args語法
  4. 捕獲異常的語法改變,引入了as關(guān)鍵字來標(biāo)識異常實(shí)例,在Py2.5中:
    >>> try: 
    ...    raise NotImplementedError('Error') 
    ... except NotImplementedError, error:

    ...    print error.message 
    ... 
    Error 
在Py3.0中: 
    >>> try: 
          raise NotImplementedError('Error') 
        except NotImplementedError as error: #注意這個(gè) as 
          print(str(error)) 
    Error 

八.模塊變動(dòng)

  1. 移除了cPickle模塊,可以使用pickle模塊代替。最終我們將會有一個(gè)透明高效的模塊。
  2. 移除了imageop模塊
  3. 移除了 audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,
    rexec, sets, sha, stringold, strop, sunaudiodev, timingxmllib模塊
  4. 移除了bsddb模塊(單獨(dú)發(fā)布,可以從http://www.jcea.es/programacion/pybsddb.htm獲取)
  5. 移除了new模塊
  6. os.tmpnam()os.tmpfile()函數(shù)被移動(dòng)到tmpfile模塊下
  7. tokenize模塊現(xiàn)在使用bytes工作。主要的入口點(diǎn)不再是generate_tokens,而是 tokenize.tokenize()

九.其它

  • xrange() 改名為range(),要想使用range()獲得一個(gè)list,必須顯式調(diào)用:
    >>> list(range(10)) 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
  • bytes對象不能hash,也不支持 b.lower()b.strip()b.split()方法,但對于后兩者可以使用 b.strip(b’ \n\t\r \f’)b.split(b’ ‘)來達(dá)到相同目的

  • zip()、map()filter()都返回迭代器。而apply()callable()coerce()、 execfile()、reduce()reload ()函數(shù)都被去除了
    現(xiàn)在可以使用hasattr()來替換 callable(). hasattr()的語法如:hasattr(string, '__name__')

  • string.letters和相關(guān)的.lowercase.uppercase被去除,請改用string.ascii_letters

  • 如果x < y的不能比較,拋出TypeError異常。2.x版本是返回偽隨機(jī)布爾值的

  • __getslice__系列成員被廢棄。a[i:j]根據(jù)上下文轉(zhuǎn)換為a.__getitem__(slice(I, j))__setitem__
    __delitem__調(diào)用

  • 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+ 主要變化或新增內(nèi)容**

```python
Python2                 Python3
print是內(nèi)置命令           print變?yōu)楹瘮?shù)
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()方法調(diào)用
x.__getslice__()        x.__getitem__()
x.__setsilce__()        x.__setitem__()
__cmp__()               刪除了__cmp__(),改用__lt__(),__gt__(),__eq__()等
reduce()                functools.reduce()
exefile(filename)       exec(open(filename).read())
0567                    0o567 (八進(jìn)制)
                        新增nonlocal關(guān)鍵字
                        str用于Unicode文本,bytes用于二進(jìn)制文本
                        新的迭代器方法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參數(shù)
                        增加Ellipse對象
                        簡化了super()方法語法
用過-t,-tt控制縮進(jìn)        混用空格與制表符視為錯(cuò)誤
from M import *可以      只能出現(xiàn)在文件的頂層
出現(xiàn)在任何位置.
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機(jī)制(類特性)
未綁定方法                都是函數(shù)
混合類型可比較排序         非數(shù)字混合類型比較發(fā)生錯(cuò)誤
/是傳統(tǒng)除法               取消了傳統(tǒng)除法, /變?yōu)檎娉?無函數(shù)注解                有函數(shù)注解 def f(a:100, b:str)->int 使用通過f.__annotation__
                        新增環(huán)境管理器with/as
                        Python3.1支持多個(gè)環(huán)境管理器項(xiàng) with A() as a, B() as b
                        擴(kuò)展的序列解包 a, *b = seq
                        統(tǒng)一所有類為新式類
                        增強(qiáng)__slot__類屬性
if X: 優(yōu)先X.__len__()    優(yōu)先X.__bool__()
type(I)區(qū)分類和類型       不再區(qū)分(不再區(qū)分新式類與經(jīng)典類,同時(shí)擴(kuò)展了元類)
靜態(tài)方法需要self參數(shù)       靜態(tài)方法根據(jù)聲明直接使用
無異常鏈                  有異常鏈 raise exception from other_exception

有什么需要隨時(shí)聯(lián)系小編??很愿意效勞


image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容