好吧,我正在做一個免費的代碼營專案,并且發生了一些很奇怪的事情,一個函式與物件實體完美配合,但另一個函式卻失敗了不知道我在整個代碼下面留下的原因可能是什么,但你應該注意的地方是第 25 行,這是導致錯誤相關函式被撤銷的原因我留下了整個代碼,因為我假設執行了這么多函式錯誤可能來自另一個,所以我想確保資訊完整。
def withdraw(self, amount, cause=False):
if self.check_funds(amount):
amount = amount * -1
if cause:
self.ledger.append('"amount" : ' str(amount) ' "description" : ' str(cause))
self.value = amount
print(self.ledger)
return True
else:
self.ledger.append('') # line 25
return True
下面的整個代碼
class Category:
def __init__(self, categorie):
self.categorie = categorie
self.value = 0
self.ledger = []
print ("el objeto " categorie " ha sido creado")
def deposit(self, amount, cause=False):
if cause:
self.ledger.append('"amount" : ' str(amount) ' "description" : ' str(cause))
self.value = amount
print(self.ledger)
else:
self.ledger.append('')
def withdraw(self, amount, cause=False):
if self.check_funds(amount):
amount = amount * -1
if cause:
self.ledger.append('"amount" : ' str(amount) ' "description" : ' str(cause))
self.value = amount
print(self.ledger)
return True
else:
self.ledger.append('')
return True
else:
return False
def get_balance(self):
return self.value
def check_funds(self, amount):
if amount > self.value:
return False
else:
return True
def transfer(self, amount, category):
if self.check_funds(amount):
category.deposit(amount, "Transfer from " self.categorie)
self.withdraw(amount, "Transfer to " category.categorie)
return True
else:
return False
def __str__(self):
asterisk = 15 - len(self.categorie) / 2
devolver = (("*"*int(asterisk)) self.categorie ("*"*int(asterisk)) "\n")
for i in self.ledger:
description = ""
amount = ""
description = i.find("description")
description = description len("description : ")
description_str = i[description:]
for char in i:
if char in "0123456789.-":
amount = char
amount_str = amount
if len(description_str) < 23:
devolver = description_str
devolver = " "*(30-len(description_str)-len(amount_str))
devolver = amount_str "\n"
else:
devolver = description_str[0:23]
devolver = " "*(30-23-len(amount_str))
devolver = amount_str "\n"
return devolver
def create_spend_chart(categories):
pass
food = Category("Food")
food.deposit(1000, "initial deposit")
food.withdraw(10.15, "groceries")
food.withdraw(15.89, "restaurant and more food for dessert")
print(food.get_balance())
clothing = Category("Clothing")
food.transfer(50, clothing)
clothing.withdraw(25.55)
clothing.withdraw(100)
auto = Category("Auto")
auto.deposit(1000, "initial deposit")
auto.withdraw(15)
print(food)
print(clothing)
print(create_spend_chart([food, clothing, auto]))
uj5u.com熱心網友回復:
問題出在__str__()方法上,而不是withdraw().
Wheni是一個空字串,for char in i:回圈不會執行,因此它不會分配amount_str. 因此,amount_str仍將包含來自前一次迭代的值。因此,任何沒有原因的分類帳條目都將顯示上一次迭代的金額。
不需要amount_str變數,它與amount在每次迭代開始時正確初始化為空字串的 相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/393376.html
