Python装饰器
发布时间:2020-12-20 10:38:25 所属栏目:Python 来源:网络整理
导读:什么是装饰器? 在不改变原来代码的基础上,修改代码的逻辑 本质就是一个高阶函数 语法糖是@ 分类 函数装饰器:定义一个函数当做装饰器 类装饰器:定义一个类当做装饰器 装饰器可以修饰普通方法,类方法,类... 装饰器可以叠加使用 ? 函数装饰器 装饰器本身
什么是装饰器?
? 函数装饰器
def decorator(func): def _decorator(*args,**kwargs): print(‘decorator called,start!‘) ret = func(*args,**kwargs) print(‘decorator called,end!‘) return ret return _decorator @decorator def test(data): print(‘test : %s‘ % data) test(‘ok‘)
def decorator(*args,**kwargs): print(args[0]) print(kwargs[‘one‘]) def _decorator(func): def __decorator(*args,**kwargs): print(‘decorator called,start!‘) ret = func(*args,**kwargs) print(‘decorator called,end!‘) return ret return __decorator return _decorator @decorator(‘x‘,one = ‘a‘) def test(data): print(‘test : %s‘ % data) test(‘ok‘) ? 类装饰器
class decorator: def __init__(self,func): self.func = func def __call__(self,*args,start!‘) ret = self.func(*args,end!‘) return ret @decorator def test(data): print(‘test : %s‘ % data) test(‘ok‘)
class decorator: def __init__(self,x): self.x = x def __call__(self,func): print(self.x) def _dectorator(*args,end!‘) return ret return _dectorator @decorator(‘a‘) def test(data): print(‘test : %s‘ % data) test(‘ok‘) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |