无参数的装饰器编写
# 装饰没有参数的函数
def function(func):
def func_in():
print("装饰")
func()
return func_in
def test():
print("无参数函数test")
f = function(test)
f()
# 完善版
@function # 相当于f = function(test)
def test_():
print('无参数函数test_')
test_()
装饰器带有参数的函数
# 装饰器带有参数的函数
def function_01(func):
def func_in(*args, **kwargs):
print("装饰")
func(*args, **kwargs)
return func_in
@function_01
def test_01(a, b):
print(f"a = {a}, b = {b}")
test_01(1, 2)
装饰带有返回值的函数
# 装饰带有返回值的函数
def function_02(func):
def func_in(*args, **kwargs):
print("装饰")
return func(*args, **kwargs)
return func_in
@function_02
def test_02(a, b):
print(f"a = {a}, b = {b}")
return a, b
print(test_02(2, 3))