检查类内部时出错

时间:2017-01-18 04:43:29

标签: python python-3.x account

我应该创建一个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

1 个答案:

答案 0 :(得分: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