-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbank_account.py
50 lines (42 loc) · 1.68 KB
/
bank_account.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import threading
def raise_exception_if_account_closed(method):
def exception_decorator(bank_account, *args):
if not bank_account.opened:
raise ValueError("Can't perform {} on a closed account.".format(method.__name__))
else:
return method(bank_account, *args)
return exception_decorator
class BankAccount(object):
def __init__(self):
self.opened = False
self.balance = 0
self.lock = threading.Lock()
@raise_exception_if_account_closed
def get_balance(self):
return self.balance
def open(self):
self.opened = True
@raise_exception_if_account_closed
def deposit(self, amount):
if amount <= 0:
raise ValueError("If you want to withdraw {}, you'll have to explicitely use the 'withdraw' service".format(-amount))
else:
self.__add_to_balance(amount)
@raise_exception_if_account_closed
def withdraw(self, amount):
if amount <= 0:
raise ValueError("If you want to deposit {}, you'll have to explicitely use the 'deposit' service".format(-amount))
else:
self.__add_to_balance(-amount)
@raise_exception_if_account_closed
def close(self):
self.opened = False
def __add_to_balance(self, value):
self.lock.acquire()
new_balance = self.balance+value
if new_balance >= 0:
self.balance = new_balance
self.lock.release()
else:
self.lock.release()
raise ValueError("Sorry, apparently we're not a real bank and you can't have a negative balance. Performing the action you asked for would result in a total balance of", new_balance)