类方法更改该类的所有变量

2024-04-26 14:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个类,然后有我可以存款和取款的类别。我遇到的问题是,当我以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)

1条回答
网友
1楼 · 发布于 2024-04-26 14:46:22

使类变量成为对象变量

class Category:

    def __init__(self, name):
        self.name=name
        self.ledger=list()
        self.runningBalance=int()
    
    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)

输出:

[{'amount': 1000, 'description': 'Initial1'}]
[{'amount': 500, 'description': 'Initial2'}]
Clothing Food

相关问题 更多 >