装饰器
函数修饰器
修饰带有返回值的函数
修改返回值:
def w_test(func):
def inner():
print('w_test inner called start')
str = func()
print('w_test inner called end')
return str.lower()
return inner
@w_test
def test():
print('this is test fun')
return 'HELLO'
ret = test()
print('ret value is %s' % ret)
装饰器带参数,函数不带参数:
def func_args(pre='xiaoqiang'):
def w_test_log(func):
def inner():
print('...记录日志...visitor is %s' % pre)
func()
return inner
return w_test_log
# 带有参数的装饰器能够起到在运行时,有不同的功能
# 先执行func_args('wangcai'),返回w_test_log函数的引用
# @w_test_log
# 使用@w_test_log对test_log进行装饰
@func_args('wangcai')
def test_log():
print('this is test log')
test_log()
修饰类
def register():
def _mock_wrapper(_class):
return _class
return _mock_wrapper
class A:
def __init__(self):
pass
def q(self):
print(333)
@classmethod
def t(cls):
print(1111)
@register() # 必须带括号,不带括号是当作函数使用
class B(A):
def t2(self):
print(2222)
用类方法的装饰器
class Docker:
subcommands = []
@classmethod
def subcommand(cls, sub_class):
cls.subcommands.append(sub_class)
del sub_class
@Docker.subcommand
class Search:
...