decorator
# 无参仅需2层函数
def log_print(func):
def wrapper(*args, **kwargs):
print("before " + func.__name__)
result = func(*args, **kwargs)
print("after " + func.__name__)
return result
return wrapper
# 有参3层函数
def log_print2(params: bool = False):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"bool:{params}")
print("before " + func.__name__)
result = func(*args, **kwargs)
print("after " + func.__name__)
return result
return wrapper
return decorator
def test(a, b):
print(f"入参项为:{a},{b}")
return a + b
@log_print2(params=True)
def test2(a, b):
print(f"入参项为:{a},{b}")
return a + b
test(1, 2)
test2(1, 2)`
装饰器2
import functools
def my_demo_new(name = any,value = any):
def my_demo(f):
print(f"my_demo function {name} {value}")
@functools.wraps(f)
def wrapper(*args, **kwargs):
print("wrapper of my_demo")
return f(*args, **kwargs)
return wrapper
return my_demo
@my_demo_new(value="AAA",name="1111")
def test(x,y,z):
"""
hello test
"""
print("test function {}".format(x))
test(1,2,3)
test.__name__
test.__doc__