-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20.closures_decorators.py
More file actions
81 lines (49 loc) · 1.34 KB
/
20.closures_decorators.py
File metadata and controls
81 lines (49 loc) · 1.34 KB
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
# Example 1 : A simple closure function.
print('>>>> Example - 1 >>>>')
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
times_3 = make_multiplier_of(3)
times_5 = make_multiplier_of(5)
print(times_3(9))
print(times_5(3))
print(times_5(times_3(2)))
# Example 2 : A simple decorators function.
print('\n')
print('>>>> Example - 2 >>>>')
def make_pretty(func):
def inner_fun():
print("I got decorated")
func()
return inner_fun
def ordinary():
print("I am ordinary")
# call ordinary() function.
ordinary()
# let's decorate this ordinary function.
pretty = make_pretty(ordinary)
pretty()
# Example 3 : @ symbol along with the name of the decorator function.
print('\n')
print('>>>> Example - 3 >>>>')
@make_pretty
def ordinary():
print("I am ordinary function as decorator function")
# call ordinary() function as decorator function.
ordinary()
# Example 4 : @ symbol along with the name of the decorator function with parameters.
print('\n')
print('>>>> Example - 4 >>>>')
def smart_divide(func):
def divide_fun(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return divide_fun
@smart_divide
def divide(a, b):
print(a / b)
divide(4, 2)