在python中创建银行帐户时需要了解我的错误

时间:2016-11-27 06:24:11

标签: python python-3.5

我有一个项目来创建银行帐户类,添加方法并使用存款和取款方法增加/减少帐户持有人的余额。这是代码:

class BankAccount():

    interest = 0.01

    def __init__(self, acct_name, acct_num, balance):
        self.acct_num = acct_num
        self.acct_name = acct_name
        self.balance = balance

    def deposit(self, amount):
        """Make a deposit into the account."""
        self.balance = self.balance + int(amount)

    def withdrawal(self, amount):
        """Make a withdrawal from the account."""
        self.balance = self.balance - amount

    def add_interest(self, interest):
        """Add interest to the account holder's account."""
        self.balance = self.balance * interest

    def acct_info(self):
        print("Account Name - " + self.acct_name + ":" + " Account Balance - " + int(self.balance) + ":" + " Account Number - " + self.acct_num + ".")

acct1 = BankAccount('Moses Dog', '554874D', 126.90)
acct1.deposit(500)
acct1.acct_info()
print(" ")

acct2 = BankAccount('Athena Cat', '554573D', '$1587.23')
acct2.acct_info()
print(" ")

acct3 = BankAccount('Nick Rat', '538374D', '$15.23')
acct3.acct_info()
print(" ")

acct4 = BankAccount('Cassie Cow', '541267D', '$785.23')
acct4.acct_info()   
print(" ")

acct5 = BankAccount('Sam Seagull', '874401D', '$6.90')
acct5.acct_info()
print(" ")

当我调用acct1.deposit(500)方法时,我得到"不能隐式地将int对象转换为字符串"。

如果我将int(金额)更改为str(金额)并运行它,它会将500附加到当前余额。

任何帮助将不胜感激。我理解是否有任何批评。我用Google搜索了,但我没有完全关注。

2 个答案:

答案 0 :(得分:2)

这里有一些提示:

>>> '$300.10' + 500  # adding a string to an int
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

>>> 300.10 + 500  # adding a float to an int
800.1

>>> '$300.10' + str(500)   # When using strings
'$300.10500'

>>> print(300.10)        # loss of zero
300.1

>>> print('${:.2f}'.format(300.10))  # formatting
$300.10

确保您使用的是正确类型的余额,存款和提款值。使用格式来保留小数点后的位数。

请参阅Format Specification Mini-Language

答案 1 :(得分:0)

在acct_info()中尝试将其更改为:

def acct_info(self):
  print("Account Name - "+self.acct_name + ":"+" Account Balance - "+  str(self.balance) +":" +" Account Number - "+self.acct_num + ".")