python 2とpython 3の区別整理(博采衆長)

31261 ワード

作業中に発生した問題は、旧版python 2で書かれた自動化テストフレームワークを3.7にアップグレードする必要がある.アップグレードの過程でいくつかの問題を発見し、ネット上の多くの資料を探した.後で一部を整理して、それからネット上のいくつかの優秀なブログの文章を結びつけて自分の修正と補充を行いました.
文書ディレクトリ
  • 1.パフォーマンス
  • 2.コード
  • 三.構文
  • 1. 削除しました<>、変更!=
  • 2. asとwithキーワードが追加され、True、False、None
  • も追加されました.
  • 3. 整型トリガ戻り浮動小数点数、整除使用//
  • 3. nonlocal文
  • を追加
  • 4. print文を除去し、print()関数
  • を追加
  • 5. 削除raw_input,input関数
  • を加える
  • 6. 新しいsuper()は、super()に
  • を渡さなくてもよい.
  • 7. 順序変更オペレータの動作
  • 8. 新式の8進変数
  • 9. 文字列およびバイト列
  • 10. データ型
  • 11. オブジェクト向け
  • 12. 異常
  • 13. 反復可能オブジェクト
  • を返します.
  • 14. forループ変数とグローバルネーミングスペースの漏洩
  • 一.パフォーマンス
    python3.x開始比python 2.x効率は低いが、3.x後には極めて大きな最適化空間があり、性能的に追いかけている.
    二.エンコーディング
    Python 3はUnicode文字のオリジナルサポートを行う.
    python 2ではASCIIコードをデフォルトの符号化方式として使用し、stringにはstrとunicodeの2種類がある.python 3はunicodeのstringのみをサポートする.
    Python2
    Python3
    表現形式
    へんかん
    さぎょう
    unicode
    str
    バイト
    decode
    表示
    str
    bytes
    バイト
    encode
    ストレージ
    # python2:
    >>> print type(unicode('this is like a python3 str type'))
    <type 'unicode'>
    
    >>> print type(b'byte type does not exist')
    <type 'str'>
    
    >>> print 'they are really' + b' the same'
    they are really the same
    
    >>> print type(bytearray(b'bytearray oddly does exist though'))
    <type 'bytearray'>
    
    # python3:
    >>> print('strings are now utf-8 \u03BCnico\u0394é!')
    strings are now utf-8 μnicoΔé!
    >>> print(type('strings are now utf-8 \u03BCnico\u0394é!'))
    <class 'str'>
    
    >>> print('python3 has', type(b' bytes for storing data'))
    python3 has <class 'bytes'>
    
    >>> print(' also has', type(bytearray(b'bytearrays')))
     also has <class 'bytearray'>
      
    >>> 'note that we cannot add a string' + b'bytes for data'
    Traceback (most recent call last):
      File "", line 1, in <module>
    TypeError: must be str, not bytes
    

    python 3はデフォルトでutf-8符号化を用いる、変数名をより広くする.
    >>>    = 'china' 
    >>>print(  ) 
    china
    
    # python2.x
    >>> str = "       "
    >>> str
    '\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
    >>> str = u"       "
    >>> str
    u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'
    
    # python3.x
    >>> str = "       "
    >>> str
    '       '
    

    三.構文
    1.削除しました<>、変更!=
    # python2:
    >>> 1 <> 2
    True
    >>> 1 != 2
    True
    
    # python3:
    >>> 1 <> 2
      File "", line 1
        1 <> 2
           ^
    SyntaxError: invalid syntax
    >>> 1 != 2
    True
    

    2.asとwithのキーワードが入っていて、True、False、Noneも入っています
    TrueとFalseはPython 2の2つのグローバル変数(名前)であり、数値的にはそれぞれ1と0に対応しています.変数である以上、他のオブジェクトを指すことができます.たとえば、次のようになります.
    >>> True = False
    >>> True
    False
    >>> True is False
    True
    >>> False = "a"
    >>> False
    'a'
    >>> if False:
    ...     print "false is True"
    ...
    false is True
    

    上のコードはPythonの設計哲学Explicit is better than implicit.に反しています.Python 3はこの欠陥を修正し、TrueとFalseは2つのキーワードになり、永遠に2つの固定されたオブジェクトを指し、再割り当ては許されない.
    >>> True = False
      File "", line 1
    SyntaxError: can't assign to keyword
    

    3.整型トリガ戻り浮動小数点数、整除使用//
    python 2.x中/除算は私たちがよく知っている多くの言語と似ています.例えばJavaやCは差が少なく、整数を除いた結果は整数で、小数点を完全に無視し、浮動小数点除算は小数点の部分を残して浮動点の結果を得ることができます.
    python 3.x中/除算はこれ以上行われず,整数間の相殺に対しても結果は浮動小数点数となる.
    # python2:
    >>> 5/3
    1
    >>> 5.0/3
    1.6666666666666667
    
    # python3:
    >>> 5/3
    1.6666666666666667
    >>> 5.0/3
    1.6666666666666667
    

    //除算(floor除算)では、python 2で除算の結果を自動的にfloor操作します.xとpython 3.xでは一致しています.
    3.nonlocal文を入れる
    python 2では、キーワードglobalを使用して変数をグローバル変数として宣言することができますが、ネスト関数では、変数を非ローカル変数として宣言するには実現できません.python 3には、キーワードnonlocalが加わる.
    def func():
      a = 1
    	def inner():
        a = 11
        inner()
        print(a)
    func()  
    # 1
    
    def funcNonlocal():
      a = 1
    	def inner():
        nonlocal a
        a = 11
        inner()
        print(a)
    funcNonlocal() 
    # 11
    

    4.print文を削除し、print()関数を追加
    python 2ではprintは文であり、python 3では関数として存在する.
    # 2:
    print("python2")
    
    # 3:
    print("python3")
    

    上記のコードは出力結果においては同じであるが、Python 2では("python 2")を全体とし、後者print()は"python 3"文字列をパラメータとして受信関数である.
    # python2:
    >>> print("a")
    a
    >>> print("a","b")
    ('a', 'b')
    
    # python3:
    >>> print("a")
    a
    >>> print("a","b")
    a b
    

    上記のコードから分かるように、python 2ではprint文の後ろにメタグループオブジェクトが接続する.比較するpython 3ではprint関数は任意の位置パラメータを受け入れることができる.python 2でprintを関数として使用する場合はfutureモジュールのprint_をインポートできます.function.
    # python2:
    >>> print("a")
    a
    >>> print("a","b")
    ('a', 'b')
    
    >>> from __future__ import print_function
    >>> print("a","b")
    a b
    

    5.raw_を取り除くinput、input関数を追加する
    Python 3では、ユーザの入力をstrオブジェクトとして格納する問題が解決されている.
    6.新しいsuper()は、super()にパラメータを渡さなくてもよい
    class A(object):
      	def __init__(self, a):
          	print("A", a)
    
    class B(A):
      	def __init__(self, a):
          	super().__init__(a)  
    

    7.順序オペレータの動作を変更
    例えば、x# python2: >>> 2 < "a" True # python3: >>> 2 < "a" Traceback (most recent call last): File "", line 1, in <module> TypeError: ' not supported between instances of 'int' and 'str'
    8.新式の8進変数
    # python2:
    >>> 0666
    438
    >>> 0777
    511
    
    # python3:
    >>> 0666
      File "", line 1
        0666
           ^
    SyntaxError: invalid token
    >>> 0o666
    438
    >>> 0o777
    511
    

    9.文字列およびバイト列
    python 2では、文字列は8-bit文字列で格納されます.
    python 3では、文字列は16-bit Unicode文字列で格納されます.文字列はstrの1つのタイプしかありません.
    10.データ型
    pthon3.xはlongタイプを除いて、ただ1種の整型----int python 3がlong+int双整数実現の方法を徹底的に廃棄し、intに統一し、高精度整数演算をサポートする.
    bytesタイプが追加されました.2に対応します.xバージョンの8ビット列:
    # python2:
    >>> a = b"china"
    >>> a
    'china'
    >>> type(a)
    <type 'str'>
    
    # python3:
    >>> a = b"china"
    >>> a
    b'china'
    >>> type(a)
    <class 'bytes'>
    

    strオブジェクトとbytesオブジェクトは使用できる.encode()はstrをbytesに変換するか、使用する.decode()bytesをstrに置き換える.
    11.オブジェクト向け
    抽象ベースクラスの導入
    12.異常
  • すべての例外はBaseExceptionから継承され、StandardError
  • が削除されました.
  • python2:
    try:
    	pass
    except Exception, e:
    	pass
    
    python3:
    try:
    	pass
    except Exception as e:
    	pass
    

  • 13.反復可能なオブジェクトを返す
    python 2にはリストを返すオブジェクトの内蔵関数やメソッドが多く、python 3では反復器のようなオブジェクト(反復可能なオブジェクト)を返すように変更するが、反復器の不活性なロード特性により大きなデータを操作する際により効率的になる.例えばpython 2のrangeとxrange関数はpython 3のrangeを合成する(2と3を同時に互換する).
    # python2:
    print range(3) 
    print type(range(3))
    # [0, 1, 2]
    # < type ‘list’>
    
    # python3:
    print(range(3))
    print(type(range(3)))
    print(list(range(3)))
    # range(0, 3)
    # < class ‘range’>
    # [0, 1, 2]
    

    それ以外に、辞書オブジェクトのdict.keys()、dict.values()、dict.items()メソッドはリストを返すのではなく、反復器のような「view」オブジェクトで返す.高次関数map,filter,zipが返すのもリストオブジェクトではない.python 2における反復器はnext法を実現する必要があり、Python 3では__next__に変更する.
    14.forループ変数とグローバルネーミングスペースの漏洩
    python 3でforループ変数はネーミングスペースの漏洩を招く.
    # python2:
    i = 1
    print 'before: i =', i
    print 'comprehension: ', [i for i in range(5)]
    print 'after: i =', i
    
    # before: i = 1
    # comprehension: [0, 1, 2, 3, 4]
    # after: i = 4
    
    # python3:
    i = 1
    print('before: i =', i)
    print('comprehension:', [i for i in range(5)])
    print('after: i =', i)
    
    # before: i = 1
    # comprehension: [0, 1, 2, 3, 4]
    # after: i = 1
    

    参考:Python 2とPython 3の主な違いは何ですか?Python 2.7.xとPython 3.xの主な違いWhat’s New In Python 3.0菜鳥チュートリアル