本文共 1409 字,大约阅读时间需要 4 分钟。
@ 符号就是装饰器的语法糖,它放在函数开始定义的地方,这样就可以省略最后一步再次赋值的操作。
@wraps接受一个函数,进行装饰,并加入了复制函数名称、注释文档、参数列表等功能,这样可以是我们在装饰器里面访问在装饰之前的函数的属性
使用:装饰器多用于授权于日志
装饰器函数
from functools import wrapsdef main(func): print('is main function...') @wraps(func) def child(): print('it print before exec func...') func() print('it print after exec func...') return child@maindef alone(): print("I'm alone function ...") print(alone.__name__)alone()
装饰器类
from functools import wraps class logit(object): def __init__(self, logfile='out.log'): self.logfile = logfile def __call__(self, func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + " was called" print(log_string) # 打开logfile并写入 with open(self.logfile, 'a') as opened_file: # 现在将日志打到指定的文件 opened_file.write(log_string + '\n') # 现在,发送一个通知 self.notify() return func(*args, **kwargs) return wrapped_function def notify(self): # logit只打日志,不做别的 pass
class Person: def __init__(self): self._first_name = None def p(self): print(self.first_name)//内部调用时需去掉前下划线 @property def first_name(self): if not self._first_name: self._first_name = 'wang' return self._first_name a = Person()a.p()
转载地址:http://uwjmf.baihongyu.com/