2016-11-27 19 views
-1

我有一個項目用於創建銀行賬戶類,添加方法並使用存取方法增加/減少賬戶持有人的餘額。下面是代碼:在python中創建銀行賬戶時需要了解我的錯誤

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(amount)更改爲str(amount)並運行它,它會將500添加到當前餘額中。

任何幫助,將不勝感激。我明白是否有任何批評。我用Google搜索了,但我沒有完全遵循。

+0

''$ 1587.23''不是一個數字。 – user2357112

+1

''帳戶餘額 - 「+ int(self.balance)' - 你認爲在那裏發生了什麼? – user2357112

+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

在acct_info
+0

好的,我修復了那部分。感謝您的幫助。我正在嘗試向帳戶添加500.00的存款,但我的計劃只顯示初始金額。我爲所有問題表示歉意,但是這是踢我的屁股。 –

0

()嘗試將其更改爲:

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

感謝您的幫助。我非常感謝它。 –

+0

接受回答然後@ marquis-hinmon-sr! – Malcoolm