2017-01-18 24 views
-1

我应该创建一个Account类,它使用上面类中定义的一些函数。我在退出课程中遇到错误检查问题。在类内部检查错误

def withdraw(self, amount): 
    if amount > self.money: 
     return 'Error'  
    self.money -= amount 

>>> a = Money(5,5) 
>>> b = Money(10,1) 
>>> acct1 = Account('Andrew', a) 
>>> print(acct1) 
Andrew's account balance is $5.05 
>>> c = Money(3,50) 
>>> acct1.deposit(c) 
>>> print(acct1) 
Andrew's account balance is $8.55 
>>> acct1.withdraw(b) 
>>> print(acct1) 
Andrew's account balance is $-2.54 

输出应该是错误,但它只是计算并给我一个负平衡。

整个代码是在这里:

class Money: 
    def __init__(self, dollars = 0, cents = 00): 
     'constructor' 
     self.dollars = dollars 
     self.cents = cents 

     if self.cents > 99: 
      self.dollars += 1 
      self.cents = self.cents - 100 


    def __repr__(self): 
     'standard representation' 
     return 'Money({}, {})'.format(self.dollars,self.cents) 

    def __str__(self): 
     'returns a string representation of ($dollars.cents)' 
     if self.cents < 10: 
      return '${}.0{}'.format(self.dollars, self.cents) 
     else: 
      return '${}.{}'.format(self.dollars, self.cents) 


    def __add__(self, new): 
     'Adds two money objects together' 
     d = self.dollars + new.dollars 
     c = self.cents + new.cents 
     return Money(d,c) 


    def __sub__(self, new): 
     'Subtracts two money objects' 
     d = self.dollars - new.dollars 
     c = self.cents - new.cents 
     return Money(d,c) 

    def __gt__(self, new): 
     'computes greater then calculations' 
     a = self.dollars + self.cents 
     b = new.dollars + new.cents 
     return a > b 


class Account: 

    def __init__(self, holder, money = Money(0,0)): 
     'constructor' 
     self.holder = holder 
     self.money = money 


    def __str__(self): 

     return "{}'s account balance is {}".format(self.holder, self.money) 

    def getBalance(self): 
     return self.money 


    def deposit(self, amount): 
     self.money = self.money + amount 


    def withdraw(self, amount): 
     if amount > self.money: 
      return 'Error'  
     self.money -= amount 
+0

可你给出你会怎么为例调用'withdraw()'? –

+0

我编辑了OP – Andrew

+0

如果您在提款函数中打印金额的值,您会得到什么? – Zeokav

回答

2

其实那是因为你没有正确计算你__gt__里面的“平衡”。

的美元应乘以100:

def __gt__(self, new): 
    a = self.dollars * 100 + self.cents 
    b = new.dollars * 100 + new.cents 
    return a > b 

可选:而不是返回'Error'你应该考虑抛出一个异常:

def withdraw(self, amount): 
    if amount > self.money: 
     raise ValueError('Not enough money') 
    self.money -= amount 
+0

我知道这是其他地方的错误。非常感谢! – Andrew

+0

@Andrew我已经更新了答案,我使用了错误的操作符。 :( – MSeifert