Python3 super()和泛型类

Mik*_*kay 3 python super python-3.x

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

#!/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)
Run Code Online (Sandbox Code Playgroud)

这引起了:

AttributeError: 'super' object has no attribute 'method'
Run Code Online (Sandbox Code Playgroud)

现在的问题是-如何运行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)
Run Code Online (Sandbox Code Playgroud)

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

Sve*_*ach 12

你的super()电话是错的.它应该是

super(B, self).method()
Run Code Online (Sandbox Code Playgroud)

或者在Python 3.x中也是如此

super().method()
Run Code Online (Sandbox Code Playgroud)

此外,不要使用dict变量名称 - 这将影响内置类.