Python3 super()和泛型类

时间:2011-03-09 15:41:54

标签: python python-3.x super

我相信一个测试用例胜过千言万语:

#!/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)

问题是 - 我如何选择我感兴趣的哪个家长班?

3 个答案:

答案 0 :(得分:12)

您的super()电话错误。它应该是

super(B, self).method()

或在Python 3.x中也只是

super().method()

此外,不要将dict用作变量名 - 这会影响内置类。

答案 1 :(得分:0)

或者,您可以像这样调用parents方法:

dict = BaseForC.method(self)

答案 2 :(得分: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

你必须使用旧的方法来调用Parent类的功能。像这样

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