-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths12_python_decorators.py
More file actions
80 lines (48 loc) · 1.47 KB
/
s12_python_decorators.py
File metadata and controls
80 lines (48 loc) · 1.47 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
def hello(name='Jose'):
print('This hello() function has been executed!')
def greet():
return '\t This is the greet() func inside hello!'
def welcome():
return '\t This is welcome() inside hello'
# print(greet())
# print(welcome())
# print('This is the end of the hello function')
print('I am going to return a function')
if name == 'Jose':
return greet()
else:
return welcome()
my_new_func = hello('Jose')
print(my_new_func)
# Example nr.1 - return function
def cool():
def super_cool():
return 'I am very cool!'
return super_cool
some_func = cool()
print(some_func())
# Example nr.2 - function as an argument
def hello():
return 'Hi Jose!'
def other(some_def_func):
print('Other code runs there!')
print(some_def_func())
other(hello)
def new_decorator(original_func):
def wrap_func():
print('Some extra code, before the original function')
original_func()
print('Some extra code, after the original function!')
return wrap_func
def func_needs_decorator():
print('I want to be decorated!')
decorated_func = new_decorator(func_needs_decorator)
decorated_func()
# Example with @ sintax
# Decorators often are usen in web frameworks like django and flask
# Decorators - decorate your function with some extra code
print('Example with @ sintax')
@new_decorator
def func_needs_decorator():
print('I want to be decorated!')
func_needs_decorator()