2 decorators 1
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, 40)
print(r)
Execution result of two decorators 1
start
func: add_num
args: (10, 20)
kwargs: {}
result: 30
end
30
If you change the order of @print_info and @print_more The execution result is
Execution result when replaced
func: wrapper
args: (10, 40)
kwargs: {}
start
end
result: 50
50
Becomes
this is, As below It may be a little easier to understand if you write it without using @. .. ..
2 decorators 2
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
def add_num(a, b):
return a + b
f = print_info(print_more(add_num))
r = f(10, 40)
print(r)
Execution result of two decorators 2
start
func: add_num
args: (10, 20)
kwargs: {}
result: 30
end
30
An image that wraps print_more in print_info. .. ..
Recommended Posts