Python の拡張 - super() の使用 Python 3 と Python 2 の比較 質問する

Python の拡張 - super() の使用 Python 3 と Python 2 の比較 質問する

もともと私が聞きたかったのはこの質問、しかし、それはすでに以前に考えられていたことがわかりました...

グーグルで調べてみたら、こんな例が見つかりましたconfigparser の拡張以下は Python 3 で動作します:

$ python3
Python 3.2.3rc2 (default, Mar 21 2012, 06:59:51) 
[GCC 4.6.3] on linux2
>>> from configparser import  SafeConfigParser
>>> class AmritaConfigParser(SafeConfigParser):
...     def __init__(self):
...         super().__init__()
... 
>>> cfg = AmritaConfigParser()

しかし、Python 2ではそうではありません:

>>> class AmritaConfigParser(SafeConfigParser):
...       def __init__(self):
...           super(SafeConfigParser).init()
... 
>>> cfg = AmritaConfigParser()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: must be type, not classob

それから、Pythonの新クラスと旧クラススタイルについて少し読みました(例:ここそして今、私はこう思うのです。

class MyConfigParser(ConfigParser.ConfigParser):
      def Write(self, fp):
          """override the module's original write funcition"""
          ....
      def MyWrite(self, fp):
          """Define new function and inherit all others"""

しかし、init を呼び出すべきではないでしょうか? これは Python 2 では同等でしょうか:

 class AmritaConfigParser(ConfigParser.SafeConfigParser):
    #def __init__(self):
    #    super().__init__() # Python3 syntax, or rather, new style class syntax ...
    #
    # is this the equivalent of the above ? 
    def __init__(self):
        ConfigParser.SafeConfigParser.__init__(self)

ベストアンサー1

  • super()(引数なし) は Python 3 で とともに導入されました__class__:

    super() -> same as super(__class__, self)
    

    これは、新しいスタイルのクラスに相当する Python 2 になります。

    super(CurrentClass, self)
    
  • 古いスタイルのクラスの場合は、常に以下を使用できます。

     class Classname(OldStyleParent):
        def __init__(self, *args, **kwargs):
            OldStyleParent.__init__(self, *args, **kwargs)
    

おすすめ記事