125

もともとこの質問をしたかったのですが、前に考えられていたことに気づきました...

グーグルで検索すると、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)
4

5 に答える 5

28

要するに、それらは同等です。履歴ビューを見てみましょう:

(1) 最初は、関数は次のようになります。

    class MySubClass(MySuperClass):
        def __init__(self):
            MySuperClass.__init__(self)

(2) コードをより抽象化する (そして移植性を高める)。スーパークラスを取得するための一般的な方法は、次のように考案されています。

    super(<class>, <instance>)

また、init 関数は次のようになります。

    class MySubClassBetter(MySuperClass):
        def __init__(self):
            super(MySubClassBetter, self).__init__()

ただし、クラスとインスタンスの両方を明示的に渡す必要があると、DRY (Don't Repeat Yourself) ルールが少し破られます。

(3) V3 で。より賢く、

    super()

ほとんどの場合で十分です。http://www.python.org/dev/peps/pep-3135/を参照できます

于 2012-05-07T17:22:29.607 に答える