如何在课堂上插入金额?

时间:2019-11-14 19:16:30

标签: python python-3.x

我正在尝试建立一个银行帐户系统,以便获得面向对象编程的经验。但是当我尝试增加一些钱时,我不知道该怎么办。请帮帮我!

class Account():


    def __init__(self, owner='Unknown', balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += self.amount
        print('Deposit Accepted')

    def withdraw(self, amount):
        if self.balance >= self.amount:
            self.balance -= self.amount
            print('Withdrawal Accepted')
        else:
            print('Funds Unvailable!')

    def __str__(self):
        return(f'Account owner: {self.owner} \nAccount balance: ${self.balance}')

acct1 = Account('Bati', 999)
acct1.deposit(1)
acct1.balance

我得到的错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-03ccc6c72dd3> in <module>
     21 
     22 acct1 = Account('Bati', 999)
---> 23 acct1.deposit(1)
     24 acct1.balance

<ipython-input-21-03ccc6c72dd3> in deposit(self, amount)
      7 
      8     def deposit(self, amount):
----> 9         self.balance += self.amount
     10         print('Deposit Accepted')
     11 

AttributeError: 'Account' object has no attribute 'amount'

2 个答案:

答案 0 :(得分:0)

您应该在函数的输入参数之前不使用self来重写方法:

class Account():

    def __init__(self, owner='Unknown', balance=0):
        self.owner = owner
    self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print('Deposit Accepted')

    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print('Withdrawal Accepted')
        else:
            print('Funds Unvailable!')

    def __str__(self):
        return(f'Account owner: {self.owner} \nAccount balance: (self.balance}')

acct1 = Account('Bati', 999)
acct1.deposit(1)
acct1.balance

答案 1 :(得分:0)

不要使用self.amount。您正在将金额值作为参数传递给函数。它不是该类的变量。

class Account():


    def __init__(self, owner='Unknown', balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print('Deposit Accepted')

    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print('Withdrawal Accepted')
        else:
            print('Funds Unvailable!')

    def __str__(self):
        return(f'Account owner: {self.owner} \nAccount balance: ${self.balance}')

acct1 = Account('Bati', 999)
acct1.deposit(1)
acct1.balance

这是有效的更新代码