3

テストケースは千の言葉に値すると私は信じています:

#!/usr/bin/env python3

def generate_a(key):
    class A(object):
        def method(self):
            return {'key': key,}
    return A

BaseForB = generate_a(1337)

class B(BaseForB):
    def method(self):
        dict = super(BaseForB, self).method()
        dict.update({'other_key': 0,})
        return dict

EXPECTED = {'other_key': 0, 'key': 1337,}
RESULT = B().method()

if EXPECTED == RESULT:
    print("Ok")
else:
    print("EXPECTED: ", EXPECTED)
    print("RESULT: ", RESULT)

これにより、次のことが発生します。

AttributeError: 'super' object has no attribute 'method'

問題は、どのように実行するかA.method()ですB.method()(私がやろうとしたことsuper()

編集

より適切なテストケースは次のとおりです。

#!/usr/bin/env python3

def generate_a(key):
    class A(object):
        def method(self):
            return {'key': key,}
    return A

class B(object):
    def method(self):
        return {'key': 'thisiswrong',}

BaseForC = generate_a(1337)

class C(B, BaseForC):
    def method(self):
        dict = super(C, self).method()
        dict.update({'other_key': 0,})
        return dict

EXPECTED = {'other_key': 0, 'key': 1337,}
RESULT = C().method()

if EXPECTED == RESULT:
    print("Ok")
else:
    print("EXPECTED: ", EXPECTED)
    print("RESULT: ", RESULT)

問題は、興味のある親クラスをどのように選択するかです。

4

3 に答える 3

14

あなたのsuper()電話は間違っています。そのはず

super(B, self).method()

またはPython 3.xでも

super().method()

さらに、変数名として使用しないでくださいdict。これは組み込みクラスを隠します。

于 2011-03-09T15:43:50.323 に答える
0

または、次のようにparentメソッドを呼び出すこともできます:

dict = BaseForC.method(self)
于 2011-11-13T14:02:50.820 に答える
0
class B(BaseForB):
def method(self):
    dict = super(BaseForB, self).method()
    dict.update({'other_key': 0,})
    return dict

は正しくありません。次のように書く必要があります。

class B(BaseForB):
def method(self):
    dict = super(B, self).method()
    dict.update({'other_key': 0,})
    return dict

この状況では:

class C(B, BaseForC):
def method(self):
    dict = super(C, self).method()
    dict.update({'other_key': 0,})
    return dict

親クラスの関数を呼び出すには、古い方法を使用する必要があります。このような

class C(B, BaseForC):
def method(self):
    dict = B.method(self)
    dict.update({'other_key': 0,})
    return dict
于 2013-06-10T08:56:55.180 に答える