装饰器(Decorators)是 Python 的一个��部分。简�地说:他们是修改其他函数的功能的函数。他们有助于让我们的代�更简短,也更Pythonic(Python范儿)。大多数�学者�知�在哪儿使用它们,所以我将�分享下,哪些区域里装饰器�以让你的代�更简�。 首先,让我们讨论下如何写你自己的装饰器。

这�能是最难掌�的概念之一。我们会�次�讨论一个步骤,这样你能完全�解它。

一切皆对象

首先我们��解下 Python 中的函数:

def hi(name="yasoob"): return "hi " + name print(hi()) # output: 'hi yasoob' # 我们甚至�以将一个函数赋值给一个��,比如 greet = hi # 我们这里没有在使用�括�,因为我们并�是在调用hi函数 # 而是在将它放在greet��里头。我们�试�行下这个 print(greet()) # output: 'hi yasoob' # 如果我们删掉旧的hi函数,看看会�生什么� del hi print(hi()) #outputs: NameError print(greet()) #outputs: 'hi yasoob'

在函数中定义函数

刚�那些就是函数的基本知识了。我们�让你的知识更进一步。在 Python 中我们�以在一个函数中定义�一个函数:

def hi(name="yasoob"): print("now you are inside the hi() function") def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" print(greet()) print(welcome()) print("now you are back in the hi() function") hi() #output:now you are inside the hi() function # now you are in the greet() function # now you are in the welcome() function # now you are back in the hi() function # 上�展示了无论何时你调用hi(), greet()和welcome()将会�时被调用。 # 然�greet()和welcome()函数在hi()函数之外是�能访问的,比如: greet() #outputs: NameError: name 'greet' is not defined

那现在我们知�了�以在函数中定义�外的函数。也就是说:我们�以创建嵌套的函数。现在你需��多学一点,就是函数也能返回函数。

从函数中返回函数

其实并�需�在一个函数里去执行�一个函数,我们也�以将其作为输出返回出�:

def hi(name="yasoob"): def greet(): return "now you are in the greet() function" def welcome(): return "now you are in the welcome() function" if name == "yasoob": return greet else: return welcome a = hi() print(a) #outputs: <function greet at 0x7f2143c01500> #上�清晰地展示了`a`现在指�到hi()函数中的greet()函数 #现在试试这个 print(a()) #outputs: now you are in the greet() function

�次看看这个代�。在 if/else 语�中我们返回 greet 和 welcome,而�是 greet() 和 welcome()。为什么那样?这是因为当你把一对�括�放在��,这个函数就会执行;然而如果你�放括�在它��,那它�以被到处传递,并且�以赋值给别的��而�去执行它。 你明白了�?让我��微多解释点细节。

当我们写下 a = hi(),hi() 会被执行,而由于 name �数默认是 yasoob,所以函数 greet 被返回了。如果我们把语�改为 a = hi(name = "ali"),那么 welcome 函数将被返回。我们还�以打�出 hi()(),这会输出 now you are in the greet() function。

将函数作为�数传给�一个函数

def hi(): return "hi yasoob!" def doSomethingBeforeHi(func): print("I am doing some boring work before executing hi()") print(func()) doSomethingBeforeHi(hi) #outputs:I am doing some boring work before executing hi() # hi yasoob!

现在你已�具备所有必需知识,�进一步学习装饰器真正是什么了。装饰器让你在一个函数的��去执行代�。

你的第一个装饰器

在上一个例�里,其实我们已�创建了一个装饰器�现在我们修改下上一个装饰器,并编写一个�微更有用点的程�:

def a_new_decorator(a_func): def wrapTheFunction(): print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction def a_function_requiring_decoration(): print("I am the function which needs some decoration to remove my foul smell") a_function_requiring_decoration() #outputs: "I am the function which needs some decoration to remove my foul smell" a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) #now a_function_requiring_decoration is wrapped by wrapTheFunction() a_function_requiring_decoration() #outputs:I am doing some boring work before executing a_func() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_func()

你看明白了�?我们刚刚应用了之�学习到的原�。这正是 python 中装饰器�的事情�它们�装一个函数,并且用这样或者那样的方��修改它的行为。现在你也许疑惑,我们在代�里并没有使用 @ 符�?那�是一个简短的方��生�一个被装饰的函数。这里是我们如何使用 @ ��行之�的代�:

@a_new_decorator def a_function_requiring_decoration(): """Hey you! Decorate me!""" print("I am the function which needs some decoration to " "remove my foul smell") a_function_requiring_decoration() #outputs: I am doing some boring work before executing a_func() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_func() #the @a_new_decorator is just a short way of saying: a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

希望你现在对 Python 装饰器的工作原�有一个基本的�解。如果我们�行如下代�会存在一个问题:

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

这并�是我们想�的�Ouput输出应该是"a_function_requiring_decoration"。这里的函数被warpTheFunction替代了。它�写了我们函数的�字和注释文档(docstring)。幸�的是Python�供给我们一个简�的函数�解决这个问题,那就是functools.wraps。我们修改上一个例��使用functools.wraps:

from functools import wraps def a_new_decorator(a_func): @wraps(a_func) def wrapTheFunction(): print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction @a_new_decorator def a_function_requiring_decoration(): """Hey yo! Decorate me!""" print("I am the function which needs some decoration to " "remove my foul smell") print(a_function_requiring_decoration.__name__) # Output: a_function_requiring_decoration

现在好多了。我们接下�学习装饰器的一些常用场景。

�本规范:

from functools import wraps def decorator_name(f): @wraps(f) def decorated(*args, **kwargs): if not can_run: return "Function will not run" return f(*args, **kwargs) return decorated @decorator_name def func(): return("Function is running") can_run = True print(func()) # Output: Function is running can_run = False print(func()) # Output: Function will not run

注�:@wraps接�一个函数�进行装饰,并加入了�制函数�称�注释文档��数列表等等的功能。这�以让我们在装饰器里�访问在装饰之�的函数的属性。


使用场景

现在我们�看一下装饰器在哪些地方特别耀眼,以�使用它�以让一些事情管�起��得更简�。

授�(Authorization)

装饰器能有助于检查�个人是�被授�去使用一个web应用的端点(endpoint)。它们被大�使用于Flask和Django web框架中。这里是一个例��使用基于装饰器的授�:

from functools import wraps def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): authenticate() return f(*args, **kwargs) return decorated

日志(Logging)

日志是装饰器�用的�一个亮点。这是个例�:

from functools import wraps def logit(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging @logit def addition_func(x): """Do some math.""" return x + x result = addition_func(4) # Output: addition_func was called

我敢肯定你已�在�考装饰器的一个其他�明用法了。


带�数的装饰器

�想想这个问题,难�@wraps�也是个装饰器�?但是,它接收一个�数,就�任何普通的函数能�的那样。那么,为什么我们�也那样�呢? 这是因为,当你使用@my_decorator语法时,你是在应用一个以�个函数作为�数的一个包裹函数。记�,Python里�个东西都是一个对象,而且这包括函数�记�了这些,我们�以编写一下能返回一个包裹函数的函数。

在函数中嵌入装饰器

我们回到日志的例�,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。

from functools import wraps def logit(logfile='out.log'): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + " was called" print(log_string) # 打开logfile,并写入内容 with open(logfile, 'a') as opened_file: # 现在将日志打到指定的logfile opened_file.write(log_string + '\n') return func(*args, **kwargs) return wrapped_function return logging_decorator @logit() def myfunc1(): pass myfunc1() # Output: myfunc1 was called # 现在一个�� out.log 的文件出现了,里�的内容就是上�的字符串 @logit(logfile='func2.log') def myfunc2(): pass myfunc2() # Output: myfunc2 was called # 现在一个�� func2.log 的文件出现了,里�的内容就是上�的字符串

装饰器类

现在我们有了能用于正�环境的logit装饰器,但当我们的应用的�些部分还比较脆弱时,异常也许是需�更紧急关注的事情。比方说有时你�想打日志到一个文件。而有时你想把引起你注�的问题��到一个email,�时也�留日志,留个记录。这是一个使用继承的场景,但目�为止我们�看到过用�构建装饰器的函数。

幸�的是,类也�以用�构建装饰器。那我们现在以一个类而�是一个函数的方�,��新构建logit。

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

这个实现有一个附加优势,在于比嵌套函数的方�更加整�,而且包裹一个函数还是使用跟以�一样的语法:

@logit()
def myfunc1():
    pass

现在,我们给 logit 创建�类,�添加 email 的功能(虽然 email 这个�题�会在这里展开)。

class email_logit(logit): ''' 一个logit的实现版本,�以在函数调用时��email给管�员 ''' def __init__(self, email='admin@myproject.com', *args, **kwargs): self.email = email super(email_logit, self).__init__(*args, **kwargs) def notify(self): # ��一�email到self.email # 这里就��实现了 pass

从现在起,@email_logit 将会和 @logit 产生�样的效果,但是在打日志的基础上,还会多��一�邮件给管�员。

原文地�:https://eastlakeside.gitbooks.io/interpy-zh/content/decorators/