1
def print_info(func):
def wrapper(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('end')
return result
return wrapper
def sum(a, b):
return a + b
f = print_info(sum)
r = f(10, 20)
print(r)
Execution result of 1
start
end
30
The print_info function is a decorator Decorating the sum function.
It's hard to understand if it's written as 1. It is easier to understand if you write as follows. .. ..
Also, the decorator can be reused, so based on that. .. ..
2
def print_info(func):
def wrapper(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('end')
return result
return wrapper
@print_info
def sum(a, b):
return a + b
@print_info
def sub(a, b):
return a - b
print(sum(10, 20))
print(sub(90, 20))
Execution result of 2
start
end
30
start
end
70
Recommended Posts