Python3 super() 和泛型类

标签 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'

问题是 - 如何在 B.method() 中运行 A.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)

问题是——我如何选择我感兴趣的父类?

最佳答案

您的 super() 调用是错误的。应该是

super(B, self).method()

或者在 Python 3.x 中也只是

super().method()

此外,不要使用 dict 作为变量名——这会影响内置类。

关于Python3 super() 和泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5248188/

相关文章:

python - 如何在 Python 中的某个点重新启动程序

python - 在 Python 2.7 中,通过 super(self.__class__, self)... 调用 super 构造函数不是更好吗?

python - Python 3.4 是否向后兼容 2.7 程序/库?

python - 排序双向链表 Python

python - Pandas 中 1 列中的 2 个数字相加和相减

python - 使用 if 条件列表理解以获取特定类型的文件列表

python - 为什么 find_by_css 中的第 nth-child 什么都不返回?

java - 如何在单个对象上接受泛型参数的父类(super class)型?

javascript - 函数或类之外的“ super ”-react-native

Python:捕获logging.exception()调用