-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbite_20.py
More file actions
40 lines (29 loc) · 923 Bytes
/
bite_20.py
File metadata and controls
40 lines (29 loc) · 923 Bytes
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
"""
Bite 20. Write a context manager
"""
class Account:
def __init__(self):
self._transactions = []
@property
def balance(self):
return sum(self._transactions)
def __add__(self, amount):
self._transactions.append(amount)
def __sub__(self, amount):
self._transactions.append(-amount)
# add 2 dunder methods here to turn this class
# into a 'rollback' context manager
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.balance < 0:
transactions_list = sorted(self._sorted, reverse = True)
while sum(transactions_list) < 0:
transactions_list.pop()
self._transactions = transactions_list
return self
if __name__ == "__main__":
account = Account()
with account as acc:
acc + 10
print(account.balance)