** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
non_decorator
def add_num(a, b):
return a + b
print('start')
r = add_num(10, 20)
print('end')
print(r)
result
start
end
30
You can use the "decorator" when you want to do something additional before and after calling ʻadd_num ()`.
decorator
def print_info(func):
def wrapper(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('end')
return result
return wrapper
def add_num(a, b):
return a + b
f = print_info(add_num)
r = f(10, 20)
print(r)
result
start
end
30
For * args
, 52. Tupleization of positional arguments
For ** kwargs
, see 53. Dictionary of keyword arguments.
If you write as above, it is difficult to understand that you are using it as a decorator. Therefore, in general, when using a decorator, describe as follows.
decorator
def print_info(func):
def wrapper(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('end')
return result
return wrapper
@print_info
def add_num(a, b):
return a + b
r = add_num(10, 20)
print(r)
result
start
end
30
By specifying a decorator function using @
, you can decorate using that function.
Write another decorator function and try using both.
two_decorators
def print_more(func):
def wrapper(*args, **kwargs):
print('func: ', func.__name__)
print('args: ', args)
print('kwargs: ', kwargs)
result = func(*args, **kwargs)
print('result: ', result)
return result
return wrapper
def print_info(func):
def wrapper(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('end')
return result
return wrapper
@print_info
@print_more
def add_num(a, b):
return a + b
r = add_num(10, 20)
print(r)
result
start
func: add_num
args: (10, 20)
kwargs: {}
result: 30
end
30
If you specify a decorator like this,
You can see that print_more
is included in print_info
.
Now try swapping the order of the two decorators.
two_decorators
def print_more(func):
def wrapper(*args, **kwargs):
print('func: ', func.__name__)
print('args: ', args)
print('kwargs: ', kwargs)
result = func(*args, **kwargs)
print('result: ', result)
return result
return wrapper
def print_info(func):
def wrapper(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('end')
return result
return wrapper
@print_more
@print_info
def add_num(a, b):
return a + b
r = add_num(10, 20)
print(r)
result
func: add_num
args: (10, 20)
kwargs: {}
start
end
result: 30
30
This time, print_info
is included in print_more
.
Recommended Posts