简体   繁体   中英

Classes in Python 2.7 - not sure what's wrong

Just a simple program to deposit and withdraw from an account. I'm trying to learn classes by just testing them out.

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()

That problem I'm having is probably best seen from the output.

For example, here is the output.

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

Not exactly sure what's happening.

I'm sure I could fix it by just manually entering (-n) or (+n) and only have one method, but I'd like to avoid that.

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.

To do what you want you need to use class variables not object variables. These are defined and used by the class as a whole as seen below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM