【问题标题】:How can insert amount to class?怎样才能插入类?
【发布时间】:2019-11-14 19:16:30
【问题描述】:

我正在尝试制作一个银行帐户系统,以便获得面向对象编程的经验。但是当我尝试添加一些钱时,我不明白该怎么做。请帮帮我!

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'

【问题讨论】:

  • 不清楚是什么问题。您具体要问什么?
  • self.balance += self.amount 可能应该是 self.balance += amount,与其他方法相同。 amount 是一个参数,不是类的成员。

标签: python python-3.x


【解决方案1】:

不要使用 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

这是一个有效的更新代码

【讨论】:

  • 也谢谢你,但另一个人也回答了。不过也谢谢你!!
【解决方案2】:

你应该在函数的输入参数之前重写没有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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多