python3 super_Python3 super()和泛型类

该博客探讨了一个在Python代码中使用super()引发AttributeError的问题。作者提供了一个测试用例,展示了如何在子类的方法中调用父类的方法。问题在于super()的使用不正确。解决方案是修正super()调用,使其为super(B, self).method()或在Python 3.x中使用super().method()。此外,建议避免使用内置名称'dict'作为变量名。
摘要由CSDN通过智能技术生成

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

#!/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作为变量名 – 这将影响内置类.

标签:python,python-3-x,super

来源: https://codeday.me/bug/20190715/1471633.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值