加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python3 super()和泛型类

发布时间:2020-12-20 12:17:52 所属栏目:Python 来源:网络整理
导读:我相信一个测试用例胜过千言万语: #!/usr/bin/env python3def generate_a(key): class A(object): def method(self): return {'key': key,} return ABaseForB = generate_a(1337)class B(BaseForB): def method(self): dict = super(BaseForB,self).method(
我相信一个测试用例胜过千言万语:

#!/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,}
RESULT = C().method()

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

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

解决方法

你的super()调用是错误的.它应该是

super(B,self).method()

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

super().method()

此外,不要使用dict作为变量名 – 这将影响内置类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读