我试着把我的脑袋绕在课堂上,我看不出我在这个剧本里做错了什么。我已经构建了一些嵌套类。在
import random
class Account(object):
num_accounts = 0
def __init__(self, name, balance):
self.name = name
self.balance = balance
Account.num_accounts += 1
def withdraw(self, amt):
self.balance = self.balance - amt
def inquiry(self):
return self.balance
class EvilAccount(Account):
def __init__(self,name,balance,evilfactor):
Account.__init__(self,name,balance)
self.evilfactor = evilfactor
def inquiry(self):
if random.randint(0,4) == 1:
return self.balance * self.evilfactor
else:
return self.balance
class MoreEvilAccount(EvilAccount):
def deposit(self,amount):
self.withdraw(5.00)
EvilAccount.deposit(self,amount)
class WithdrawCharge(object):
fee = 2.50
def withdraw_fee(self):
self.withdraw(self.fee)
class MostEvilAccount(EvilAccount,
WithdrawCharge):
def withdraw(self,amt):
self.withdraw_fee()
super(MostEvilAccount,self).withdraw(amt)
然后我用
^{pr2}$一切都很好。但是当我试图调用继承的方法时:
d.withdraw(5.00)
我得到递归错误!在
File "StackO.py", line 37, in withdraw
self.withdraw_fee()
File "StackO.py", line 33, in withdraw_fee
self.withdraw(self.fee)
File "StackO.py", line 37, in withdraw
self.withdraw_fee()
RecursionError: maximum recursion depth exceeded
这是由davidm.Beazley撰写的Python基本参考,p121。在
为什么我得到递归错误?在
您的问题是}上,因为传入}是
WithdrawCharge
实际上没有一个名为withdraw
的方法。因此,当您从MostEvilAccount
上的withdraw
调用它时,Python必须搜索一个适当的方法,即withdraw
在{WithdrawCharge.withdraw_fee
的{MostEvilAccount
。举例说明:它还在继续。。。在
有几种方法可以解决这个问题。您可以使用
WithdrawCharge
的功能并将其嵌入MostEvilAccount.withdraw
。您还可以将Account.withdraw
作为参数传递给withdraw_fee
,并让它调用它。在此错误用于防止堆栈溢出。有关如何工作的详细信息here
相关问题 更多 >
编程相关推荐