-
Notifications
You must be signed in to change notification settings - Fork 24
/
account.py
83 lines (65 loc) · 2.48 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from functools import total_ordering
@total_ordering
class Account:
'A simple account class'
def __init__(self, owner, amount=0):
'This is the constructor that lets us create objects from this class'
self.owner = owner
self.amount = amount
self._transactions = []
def __repr__(self):
return 'Account({!r}, {!r})'.format(self.owner, self.amount)
def __str__(self):
return 'Account of {} with starting amount: {}'.format(self.owner,
self.amount)
def add_transaction(self, amount):
if not isinstance(amount, int):
raise ValueError('please use int for amount')
self._transactions.append(amount)
@property
def balance(self):
return self.amount + sum(self._transactions)
def __len__(self):
return len(self._transactions)
def __getitem__(self, position):
return self._transactions[position]
def __reversed__(self):
return self[::-1]
def __eq__(self, other):
return self.balance == other.balance
def __lt__(self, other):
return self.balance < other.balance
def __add__(self, other):
owner = '{}&{}'.format(self.owner, other.owner)
start_amount = self.amount + other.amount
acc = Account(owner, start_amount)
for t in list(self) + list(other):
acc.add_transaction(t)
return acc
def __call__(self):
print('Start amount: {}'.format(self.amount))
print('Transactions: ')
for transaction in self:
print(transaction)
print('\nBalance: {}'.format(self.balance))
def __enter__(self):
print('ENTER WITH: making backup of transactions for rollback')
self._copy_transactions = list(self._transactions)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('EXIT WITH:', end=' ')
if exc_type:
self._transactions = self._copy_transactions
print('rolling back to previous transactions')
print('transaction resulted in {} ({})'.format(exc_type.__name__, exc_val)) # noqa E501
else:
print('transaction ok')
if __name__ == '__main__':
acc = Account('bob', 10)
acc.add_transaction(20)
acc.add_transaction(-10)
acc.add_transaction(50)
acc.add_transaction(-20)
acc.add_transaction(30)
assert acc.balance == 80
assert list(reversed(acc)) == [30, -20, 50, -10, 20]