-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21decorator_in_python.py
More file actions
151 lines (74 loc) · 2.37 KB
/
21decorator_in_python.py
File metadata and controls
151 lines (74 loc) · 2.37 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#passing function as an argument
# def function1():
# print("Hello from function 1")
# def function2(func):
# print("Hello from function 2")
# func()
# function2(function1)
#returning function from another function
# def function3():
# print("Hello from function 3")
# def function4():
# print("Hello from function 4")
# return function4
# # function3()()
# func_var=function3()
# func_var()
#Decorator
#a decorator is a function that takes another function and extends or alters its behaviour
# def decorator(func):
# def wrapper():
# print("Transaction initiated")
# func()
# print("Transaction completed")
# return wrapper
# def hello():
# print("Transaction is in process")
# decorated_func=decorator(hello) ## hello function modified by decorator
# decorated_func()
#shortcut
# @decorator
# def hello():
# print("Transaction is in process")
# hello()
# import math
# def square_root(num):
# sq_root=math.sqrt(num)
# return sq_root
# #decorator
# def decorator_positive(func):
# def wrapper(num):
# if num<0:
# print("Square root of negative number is not possible")
# raise ValueError
# else:
# sq_root=func(num)
# return sq_root
# return wrapper
# using a decorator
# new_decorated_func=decorator_positive(square_root)
# print(new_decorated_func(16))
# print(new_decorated_func(-16)) #returns error
# shorhand decorator to use decorator
# @decorator_positive
# def area_of_square_land(length):
# area=length**2
# return area
# print(area_of_square_land(5))
# import time
# def decorator_time(func):
# def wrapper():
# start_time=time.time() #For example, if time.time() returns a value of 1665043212.1234567, it means that 1,665,043,212 seconds have passed since the Unix epoch (January 1, 1970, 00:00:00 UTC).
# func()
# end_time=time.time()
# print(end_time-start_time)
# return wrapper
# @decorator_time
# def function1():
# print("Hello from function 1")
# function1()
# @decorator_time
# def function2():
# for i in range(200):
# print(i)
# function2()