0

只是一个简单的程序来存款和从账户中取款。我正在尝试通过测试来学习课程。

class bank:
    def __init__(self):
        self.origBal = 0
    def deposit(self, amount):
        self.origBal += amount
    def withdraw(self, amount):
        self.origBal -= amount
b = bank()
d = bank()
w = bank()

我遇到的那个问题可能最好从输出中看出。

例如,这里是输出。

w.withdraw(3423)
b.origBal
-3423
d.deposit(3423)
b.origBal
-3423
d.deposit(322423)
d.origBal
325846
d.deposit(3223)
d.origBal
329069
w.withdraw(324334)
b.origBal
-3423
w.withdraw(234)
b.origBal
-3423

不完全确定发生了什么。

我确信我可以通过手动输入 (-n) 或 (+n) 来修复它,并且只有一种方法,但我想避免这种情况。

4

2 回答 2

2

When you do b = bank() you create one bank. When you do d = bank() you create a second bank. When you do w = bank() you create a third bank. Each bank has its own origBal. Calling deposit or withdraw on one of the three objects won't affect either of the other two objects. If you do

b = bank()
b.deposit(10)
b.withdraw(100)

. . . then things should work as you seem to expect.

You should read the Python tutorial to learn how classes work.

于 2012-10-07T02:22:45.193 回答
1

要执行您想要的操作,您需要使用类变量而不是对象变量。这些由整个类定义和使用,如下所示。

class Bank(object):
    origBal = 0
    def deposit(self, amount):
        Bank.origBal += amount
    def withdraw(self, amount):
        Bank.origBal -= amount

b = Bank()
d = Bank()
w = Bank()

w.withdraw(3423)
b.origBal
-3423
d.deposit(3423)
b.origBal
0
d.deposit(322423)
b.origBal
322423
d.deposit(3223)
b.origBal
325646
w.withdraw(324334)
b.origBal
1312
w.withdraw(234)
b.origBal
1078
于 2012-10-07T02:27:09.907 回答