<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Python2和Python3的區(qū)別?

          共 8004字,需瀏覽 17分鐘

           ·

          2021-05-23 12:39


          Python2和Python3的區(qū)別

          Python 的 3.0 版本,常被稱為 Python 3000,或簡稱 Py3k。相對于 Python 的早期版本,這是一個較大的升級。為了不帶入過多的累贅,Python3 在設(shè)計的時候沒有考慮向下相容。許多針對早期 Python 版本設(shè)計的程式都無法在 Python3 上正常執(zhí)行。

          為了照顧現(xiàn)有程式,Python 2.6 作為一個過渡版本,基本使用了 Python2 的語法和庫,同時考慮了向 Python3 的遷移,允許使用部分 Python3 的語法與函數(shù)。

          隨著 Python 語言市場份額的增長,第三方庫都正在努力地相容Python 3.x版本,所以如果想要學習 Python 的朋友們,最好從 Python3 開始學起,雖然 Python2 慢慢將淡出市場,但是我們還是有必要了解兩者之間的區(qū)別。

          1.print 函數(shù)

          print 語句沒有了,取而代之的是 print() 函數(shù)。

          Old: print "The answer is"2*2Newprint("The answer is"2*2)Old: print x,          

           # Trailing comma suppresses newlineNew: print(x, end=" ")  

          # Appends a space instead of a newlineOld: print              

          # Prints a newlineNew: print()            

          # You must call the function!Old: print >>sys.stderr, "fatal error"New: print("fatal error", file=sys.stderr)Old: print (x, y)       

          # prints repr((x, y))New: print((x, y))      

          # Not the same as print(x, y)!

          2.整除

          Python2 中 / 的結(jié)果是整型,Python3 中是浮點類型。

          Python2:

          >>> 1 / 20>>> 1.0 / 2.00.5

          Python3:

          >>1/20.5
          3.Unicode

          Python2 默認編碼是 ASCII,在使用 Python2 的過程中經(jīng)常會遇到編碼問題,當時因為 Python 語言還沒使用 Unicode,所以使用 ASCII 作為默認編碼。Python3 默認編碼是 Unicode(utf-8),也就不需要在文件頭部寫 # coding=utf-8。

          Python2:

          >>> str = "我愛北京天安門"

          >>> str'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'

          >>> sys.getdefaultencoding()'ascii'

          Python3:

          >>> str = "我愛北京天安門"

          >>> str'我愛北京天安門'

          >>> sys.getdefaultencoding()'utf-8'

          4.迭代器

          在 Python2 中很多返回列表對象的內(nèi)置函數(shù)和方法在 Python3 都改成了返回類似于迭代器的對象,因為迭代器的惰性加載特性使得操作大數(shù)據(jù)更有效率。Python2 中的 xrange 在 Python3 中重命名為 range。

          Python2:

          >>> [x for x in xrange(10)][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

          Python3:

          >>> [x for x in range(10)][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
          >>> [x for x in xrange(10)]NameError                                 
          Traceback (most recent call last)<ipython-input-2-4ecef59b8e55> in <module>()
           ----> 1 [x for x in xrange(10)]NameError: name 'xrange' is not defined

          另外,字典對象的 dict.keys()、dict.values() 方法都不再返回列表,而是以一個類似迭代器的 "view" 對象返回。Python2:

          >>>dic1={'a':1,'b':2,'c':3,'d':4,'e':5}

          >>>dic1.keys()

          >>>dic1.values()['a''c''b''e''d'][13254]

          Python3:

          >>>dic1={'a':1,'b':2,'c':3,'d':4,'e':5}

          >>>dic1.keys()

          >>>dic1.values()dict_keys(['a''b''c''d''e'])dict_values([12345])

          高階函數(shù) map、filter、zip 返回的也都不是列表對象了,對于比較高端的 reduce 函數(shù),它在 Python 3.x 中已經(jīng)不屬于 built-in 了,被挪到 functools 模塊當中。

          Python2:

          #類型是 built-in function(內(nèi)置函數(shù))

          >>> map<built-in function map

          >>>> filter<built-in function filter>#輸出的結(jié)果類型都是列表

          >>> map(lambda x:x *2, [1,2,3])[246]

          >>> filter(lambda x:x %2 ==0,range(10))[02468]

          Python3:

          >>> map<class 'map'

          >>>> map(print,[1,2,3])<map object at 0x10d8bd400

          >>>> filter<class 'filter'

          >>>> filter(lambda x:x % 2 == 0, range(10))<filter object at 0x10d8bd3c8>

          map、filter 從函數(shù)變成了類,其次,它們的返回結(jié)果也從當初的列表成了一個可迭代的對象, 我們嘗試用 next 函數(shù)來進行手工迭代。

          >>> f =filter(lambda x:x %2 ==0, range(10))

          >>> next(f)0

          >>> next(f)2

          5.不等運算符

          Python2 中不等于有兩種寫法 != 和 <>;Python3 中去掉了 <>, 只有 != 一種寫法,我并未使用過 <>。

          6.數(shù)據(jù)類型

          Python3 去除了 long 類型,現(xiàn)在只有一種整型——int,但它的行為就像 Python2 版本的 long;

          新增了 bytes 類型,對應于 Python2 版本的八位串

          7.True和False

          True 和 False 在 Python2 中是兩個全局變量(名字),在數(shù)值上分別對應 1 和 0,既然是變量,那么就可以重新指向其它對象。

          >>> False = '1'

          >>> False'1'

          >>> if False:...     

          print("?")... ?

          Python3 修正了這個缺陷,True 和 False 變?yōu)閮蓚€關(guān)鍵字,永遠指向兩個固定的對象,不允許再被重新賦值。

          >>> True = 1  

          File "<stdin>", 

          line 1  

          SyntaxError: can't assign to keyword

          8.nonlocal

          global 適用于函數(shù)內(nèi)部修改全局變量的值,但是在嵌套函數(shù)中,想要給一個變量聲明為非局部變量是沒法實現(xiàn)的,在 Python3 中,新增了關(guān)鍵字 nonlcoal,使得非局部變量成為可能。

          Python2:

          def func():   
          c = 1    def foo():        nonlocal c        
          c = 12    
          foo()    
          print(c)func()   
          File "<ipython-input-10-441055e26d24>", line 4    nonlocal c            
           ^SyntaxError: invalid syntax

          Python3:

          def func():    
          c = 1    def foo():        nonlocal c        
          c = 12    
          foo()    
          print(c)func()#12
          9.通過input()解析用戶的輸入

          在 python2 中 raw_input() 和 input(),兩個函數(shù)都存在,其中區(qū)別為:raw_input()---將所有輸入作為字符串看待,返回字符串類型;input()-----只能接收"數(shù)字"的輸入,在對待純數(shù)字輸入時具有自己的特性,它返回所輸入的數(shù)字的類型(int, float )。

          在 python3 中 raw_input() 和 input() 進行了整合,去除了 raw_input(),僅保留了 input() 函數(shù),其接收任意任性輸入,將所有輸入默認為字符串處理,并返回字符串類型。

          10.異常

          except 關(guān)鍵字的使用在 Python 3 中處理異常也輕微地改變了,在 Python 3 中我們現(xiàn)在使用 as 作為關(guān)鍵詞。

          Python2:

          print 'Python', python_version()
          try:    
          let_us_cause_a_NameErrorexcept NameError, 
          err:    print err, '
          --> our error message'
          Python 2.7.6name '
          let_us_cause_a_NameError'
           
          is not defined --> our error message

          Python3:

          print('Python', python_version())try:    
          let_us_cause_a_NameErrorexcept NameError as err:    print(err, '--> our error message')
          Python 3.4.1name 'let_us_cause_a_NameError' is not defined 
          --> our error message

          raise 語句使用逗號將拋出對象類型和參數(shù)分開,3.x取消了這種奇葩的寫法,直接調(diào)用構(gòu)造函數(shù)拋出對象即可。

          11.For 循環(huán)變量和全局命名空間泄漏

          在 Python3 中 for 循環(huán)變量不會再導致命名空間泄漏。

          "列表推導不再支持 [... for var in item1, item2, ...] 這樣的語法。使用 [... for var in (item1, item2, ...)] 代替。也需要提醒的是列表推導有不同的語義:他們關(guān)閉了在 `list()` 構(gòu)造器中的生成器表達式的語法糖, 并且特別是循環(huán)控制變量不再泄漏進周圍的作用范圍域."

          Python2:

          print 'Python', python_version()i = 1print 'before: i =', iprint 'comprehension: ',
           [i for i in range(5)]print 'after: i ='
          iPython 2.7.6before:
           i = 1comprehension:  [01234]after: 
          i = 4

          Python3:

          print('Python', python_version())
          i = 1print('before: i =', i)print('comprehension:', [i for i in range(5)])print('after: i =', i)
          Python 3.4.1before: 
          i = 1comprehension: [01234]after: i = 1
          12.繼承
          class A:     def __init__(self):        
           print("A")class B(A):     
          passclass C(A):    def __init__(self):        
          print("C")class D(B,C):    
          passd1 = D()

          Python2 結(jié)果為 A,

          Python3 結(jié)果為 C。

          python2 的繼承順序是 D -> B -> A -> C 深度優(yōu)先

          python3 的繼承順序是 D -> B -> C -> A 廣度優(yōu)先。

          一鍵三連~~

          關(guān)注小編喲~

          長按關(guān)注



          瀏覽 34
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  99热99在线观看 | 精品熟人一区二区三区四区 | 亚洲色图欧洲 | 3级中文字幕 | 高清无码做爱 |