-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchap3_code_40.py
More file actions
31 lines (24 loc) · 837 Bytes
/
chap3_code_40.py
File metadata and controls
31 lines (24 loc) · 837 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
# Lets suppose we want to decorate a class such that it prints a warning
# when we try to spend more than what we've got
def add_warning(cls):
prev_spend = getattr(cls, 'spend')
def new_spend(self, money):
if money > self.money:
print("You are spending more than what you have, "
"a debt has been generated in your account!!")
prev_spend(self, money)
setattr(cls, 'spend', new_spend)
return cls
@add_warning
class Buy:
def __init__(self, money):
self.money = money
self.debt = 0
def spend(self, money):
self.money -= money
if self.money < 0:
self.debt = abs(self.money) # the debt is considered positive
self.money = 0
print("Current Balance = {}".format(self.money))
b = Buy(1000)
b.spend(1200)