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

这可能是最难掌握的概念之一。 会每次只讨论个步骤 这样你能完全理解它。

一切皆对象

首先 来理解下 Python 中的函数:

def hi(name="yasoob"):return "hi " + nameprint(hi())# output: 'hi yasoob'# 甚至可以将个函数赋值给个变量 如greet = hi# 这里没有在使用小括号 因为 并不是在调用hi函数# 而是在将它放在greet变量里头。 尝试运行下这个print(greet())# output: 'hi yasoob'# 如果 删掉旧的hi函数 看看会发生什么!del hiprint(hi())#outputs: NameErrorprint(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 greetelse:return welcomea = hi()print(a)#outputs: #上面清晰地展示了`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 wrapTheFunctiondef 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_decoratordef 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 wrapsdef 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_decoratordef 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 wrapsdef 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_namedef func():return("Function is running")can_run = Trueprint(func())# Output: Function is runningcan_run = Falseprint(func())# Output: Function will not run

注意:@wraps接受个函数来进行装饰 并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让 在装饰器里面访问在装饰之前的函数的属性。


使用场景

现在 来看一下装饰器在哪些地方特别耀眼 以及使用它可以让一些事情管理起来变得更简单。

授权(Authorization)

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

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

日志(Logging)

日志是装饰器运用的另个亮点。这是个例子:

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

我敢肯定你已经在思考装饰器的个其 聪明用法了。


带参数的装饰器

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

在函数中嵌入装饰器

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

from functools import wrapsdef 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:# 现在将日志打到指定的logfileopened_file.write(log_string + 'n')return func(*args, **kwargs)return wrapped_functionreturn logging_decorator@logit()def myfunc1():passmyfunc1()# Output: myfunc1 was called# 现在个叫做 out.log 的文件出现了 里面的内容就是上面的字符串@logit(logfile='func2.log')def myfunc2():passmyfunc2()# Output: myfunc2 was called# 现在个叫做 func2.log 的文件出现了 里面的内容就是上面的字符串

装饰器类

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

幸运的是 类也可以用来构建装饰器。那 现在以个类而不是个函数的方式 来重新构建logit。

from functools import wrapsclass logit(object):def __init__(self, logfile='out.log'):self.logfile = logfiledef __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_functiondef 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 = emailsuper(email_logit, self).__init__(*args, **kwargs)def notify(self):# 发送一封email到self.email# 这里就不做实现了pass

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

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