如何解决为什么我不能在类之外使用 __repr__ 数据
我开始使用 Python 并努力在课堂外使用 __repr__
数据。打印数据输出一个带有列表的列表(正是我想要做的),例如:
print(test)
导致:
[['Food','-10.15','-15.89','-50'],['Clothing','-25.55'],['Auto','-15']]
我的问题是:
print(test[0])
导致意外输出,而不是:
['Food','-50']
而不是像这样的一些数据:
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
***********Clothing***********
Transfer from Food 50.00
-25.55
Total: 24.45
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
None
.***********Business***********
deposit 900.00
-10.99
class Category:
def __init__(self,category):
self.category = category
self.balance = 0
self.ledger = []
def __repr__(self):
b = []
b.append(self.category)
for obj in self.ledger:
if str(obj['amount'])[0] == "-":
b.append(str(obj['amount']))
return str(b)
def __str__(self):
lengthTop = int((30 - len(str(self.category))) / 2)
output = "*" * lengthTop + self.category + "*" * lengthTop
for entry in self.ledger:
if len(entry['description']) > 23:
x = slice(0,23)
output += "\n" + entry['description'][x] + ("{:7.2f}".format(entry['amount']))
else:
output += ("\n" + entry['description'] + (" " * (23 - int(len(entry['description'])))) + ("{:7.2f}".format(entry['amount'])))
output += "\n" + "Total:" + ("{:7.2f}".format(self.balance))
return output
def check_funds(self,amount):
if amount > self.balance:
return False
else:
return True
def deposit(self,amount,description=""):
self.balance += amount
self.ledger.append({"amount": amount,"description": description})
def withdraw(self,description=""):
if self.check_funds(amount) == True:
self.balance -= amount
self.ledger.append({"amount": -amount,"description": description})
return True
else:
return False
def get_balance(self):
return self.balance
def transfer(self,newcategory):
if self.check_funds(amount) == True:
self.withdraw(amount,"Transfer to " + newcategory.category)
newcategory.deposit(amount,"Transfer from " + self.category)
return True
else:
return False
def create_spend_chart(categories):
test = categories
print(test)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。