Python类继承:递归E

2024-06-16 12:36:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着把我的脑袋绕在课堂上,我看不出我在这个剧本里做错了什么。我已经构建了一些嵌套类。在

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。在

为什么我得到递归错误?在


Tags: nameselfreturninitdefaccountclassfile
2条回答

您的问题是WithdrawCharge实际上没有一个名为withdraw的方法。因此,当您从MostEvilAccount上的withdraw调用它时,Python必须搜索一个适当的方法,即withdraw在{}上,因为传入WithdrawCharge.withdraw_fee的{}是MostEvilAccount。举例说明:

d = MostEvilAccount("Dave", 500.00, 1)
d.withdraw(5.00)

 > In MostEvilAccount.withdraw at line 37
  > In WithdrawCharge.withdraw_fee at line 33
   > In MostEvilAccount.withdraw at line 37
    > In WithdrawCharge.withdraw_fee at line 33

它还在继续。。。在

有几种方法可以解决这个问题。您可以使用WithdrawCharge的功能并将其嵌入MostEvilAccount.withdraw。您还可以将Account.withdraw作为参数传递给withdraw_fee,并让它调用它。在

此错误用于防止堆栈溢出。有关如何工作的详细信息here

相关问题 更多 >