221

理解できないエラーが発生します。サンプル コードの何が問題なのか手がかりはありますか?

class B:
    def meth(self, arg):
        print arg

class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

「スーパー」組み込みメソッドの助けを借りて、サンプル テスト コードを取得しました。

エラーは次のとおりです。

Traceback (most recent call last):
  File "./test.py", line 10, in ?
    print C().meth(1)
  File "./test.py", line 8, in meth
    super(C, self).meth(arg)
TypeError: super() argument 1 must be type, not classobj

参考までに、これはpython自体からのヘルプ(スーパー)です:

Help on class super in module __builtin__:

class super(object)
 |  super(type) -> unbound super object
 |  super(type, obj) -> bound super object; requires isinstance(obj, type)
 |  super(type, type2) -> bound super object; requires issubclass(type2, type)
 |  Typical use to call a cooperative superclass method:
 |  class C(B):
 |      def meth(self, arg):
 |          super(C, self).meth(arg)
 |
4

4 に答える 4

363

あなたの問題は、クラス B が「新しいスタイル」のクラスとして宣言されていないことです。次のように変更します。

class B(object):

そしてそれはうまくいくでしょう。

super()すべてのサブクラス/スーパークラスのものは、新しいスタイルのクラスでのみ機能します。(object)新しいスタイルのクラスであることを確認するために、クラス定義で常にそれを入力する習慣を身につけることをお勧めします。

古いスタイルのクラス (「クラシック」クラスとも呼ばれます) は、常に 型classobjです。new-style クラスのタイプはtypeです。これが、見たエラー メッセージを受け取った理由です。

TypeError: super() argument 1 must be type, not classobj

これを試して自分の目で確かめてください:

class OldStyle:
    pass

class NewStyle(object):
    pass

print type(OldStyle)  # prints: <type 'classobj'>

print type(NewStyle) # prints <type 'type'>

Python 3.x では、すべてのクラスが新しいスタイルであることに注意してください。古いスタイルのクラスの構文を引き続き使用できますが、新しいスタイルのクラスが得られます。したがって、Python 3.x ではこの問題は発生しません。

于 2009-11-11T04:40:10.923 に答える