我试图创建一个类,然后有我可以存款和取款的类别。我遇到的问题是,当我以say food为例调用方法'deposit'时,它也会更新名为'Clothing'的对象。我相信这是一个简单的解决办法
以下代码的输出为:
[{'amount': 1000, 'description': 'Initial1'}, {'amount': 500, 'description': 'Initial2'}]
[{'amount': 1000, 'description': 'Initial1'}, {'amount': 500, 'description': 'Initial2'}]
Clothing Food
鉴于我想要:
[{'amount': 1000, 'description': 'Initial1'}]
[{'amount': 500, 'description': 'Initial2'}]
Clothing Food
有人有什么想法吗?谢谢
class Category:
ledger=list()
runningBalance=int()
name=""
def __init__(self, name):
self.name=name
def deposit(self,amount,description):
self.ledger.append({"amount":amount,"description":description})
self.runningBalance=self.runningBalance+amount
Food=Category("Food")
Clothing=Category("Clothing")
Food.deposit(1000,"Initial1")
Clothing.deposit(500,"Initial2")
print(Food.ledger)
print(Clothing.ledger)
print(Clothing.name,Food.name)
使类变量成为对象变量
输出:
相关问题 更多 >
编程相关推荐