【问题标题】:Python3 super() and generic classPython3 super() 和泛型类
【发布时间】:2011-03-09 15:41:54
【问题描述】:

我相信一个测试用例值一千字:

#!/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(),而是直接调用这个基类:BaseForC.method(self)。在 SO 上阅读 super() 的文档和 super() 上的许多老问题。
  • 当然!对此感到抱歉 - 工作日结束,我的大脑无法正常工作......

标签: python python-3.x super


【解决方案1】:

您的super() 呼叫错误。应该是

super(B, self).method()

或者在 Python 3.x 中也只是

super().method()

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

【讨论】:

  • 谢谢,我的错。编辑以纠正我的错误并显示我的实际问题
【解决方案2】:

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

dict = BaseForC.method(self)

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多