【译】Python装饰方法漫谈(一)

讲在开始

一直对Python中Decorator这个理念理解的不是很透彻,搜罗学习资料的时候发现了stackoverflow上一个略长略长但讲述清楚详尽的答案。准备利用最近的空闲时间翻译出来整理一下,当个搬运工。原答案链接在这里

上面是问题链接,这个链接直接跳到答案部分 ⬇️

http://stackoverflow.com/a/1594484

原答案代码2.7版本下可以全部运行成功,我将其中的代码用3.5版本重写,并改正了一些没有遵循PEP8规范的代码,以便自己学习理解的更深入一些

Kulbear:因为大学在国外上的,整个CS的教育背景基本是全英文,有些词翻译的可能不是很专业。现在还记得当初大一时候看书不知assignment statement是赋值语句。如果有翻译的错误,请随时指出。

基础

一切函数(Function)皆为对象(Object)

作为理解装饰器(Decorator)的重要前提,首先你要明白:Python中所有的函数都是对象

让我们来看一个简单的例子:

# -*- coding: utf-8 -*-
def shout(word="yes"):
    return word.capitalize() + "!"


print(shout())
# 输出 : Yes!

# 既然一切函数都是对象,那么你可以像赋值其他对象到一个变量一样,
# 将函数赋值给变量,如下
scream = shout

# 需要注意的是,我们没有在函数后面加上():我们并不是在调用这个函数,
# 而是在将函数shout“放入”变量scream中。
# 这意味着你可以通过scream来调用shout函数,如下
print(scream())
# 输出 : Yes!

# 此外,即使现在你删除了shout,你仍然可以通过scream调用这个函数
del shout
try:
    print(shout())
except NamError as e:
    print(e)
    # 输出 : name 'shout' is not defined

print(scream())
# 输出 : Yes!

好,牢记这一点,我们稍后还会回顾。

另一个你需要知道的特性是:在Python里,函数可以定义在另一个函数里

# -*- coding: utf-8 -*-
def talk():
    # 现在让我们在这里定义一个whisper函数 ...
    def whisper(word="yes"):
        return word.lower() + "..."

    # 直接调用whisper函数
    print(whisper())


# 你**每次**调用talk函数的时候,whisper函数都会被重新定义
# 并随后在talk内部被调用
talk()
# 输出 : yes...

# 但很明显,whisper函数在talk函数之外是undefined的
try:
    print(whisper())
except NameError as e:
    print(e)
    # 输出 : name 'whisper' is not defined
    # 牢记,Python中函数皆为对象

函数引用(Function Reference)

很高兴你持续读到了这里,有趣的才刚刚开始(讲道理,这句话我觉得很老外的语气…)

你已经明白了函数皆为对象这点,因此我们可以总结出,对于一个函数,它:

  • 可以被赋给变量
  • 可以再另一个函数中被定义

因此,一个函数可以返回(return)另一个函数

# -*- coding: utf-8 -*-
def scream(word="yes"):
    # 在原答案中没有这个函数,应该是来源于上面的代码片段
    # 这里我添加上以便每个文件可以独立执行
    return word.capitalize() + "!"


def get_talk(kind="shout"):
    def shout(word="yes"):
        return word.capitalize() + "!"

    def whisper(word="yes"):
        return word.lower() + "..."

    if kind == "shout":
        # 由于我们要返回的是函数这个对象,所以不使用(),
        return shout
    else:
        return whisper

# 如何使用?

# 获取一个函数,并把他复制给变量talk
talk = get_talk()

print(talk)
# 输出 : <function shout at 0xb7ea817c>

print(talk())
# 输出 : Yes!

# 也可以直接调用
print(get_talk("whisper")())
# 输出 : yes...


def do_something_before(func):
    print("I do something before then I call the function you gave me")
    print(func())


do_something_before(scream)
# 输出:
# I do something before then I call the function you gave me
# Yes!

好了,万事俱备,只欠东风了,理解装饰器所需要的知识点你应该已经全部具备了。

You see, decorators are “wrappers”, which means that they let you execute code before and after the function they decorate without modifying the function itself.

动手写一个装饰器吧

简单来说,装饰器就是一个接受其他函数为参数的函数

def my_shiny_new_decorator(a_function_to_decorate):
    # 这个函数“包装”了上面传入的函数,并且在被包装的函数前后
    # 当前函数可以添加执行一些别的代码
    def the_wrapper_around_the_original_function():
        # 被包装的函数之前要执行的代码部分
        print("Before the function runs")

        # 调用传入的函数a_function_to_decorate
        # 因为是调用,所以要带有()
        a_function_to_decorate()

        # 被包装的函数之后要执行的代码部分
        print("After the function runs")

    # 此时, "a_function_to_decorate" 从未被执行过.
    # 我们返回“包装”用的这个函数 "the_wrapper_around_the_original_function"
    return the_wrapper_around_the_original_function


# 现在,创建一个之后不做更改的函数
def a_stand_alone_function():
    print("I am a stand alone function")


a_stand_alone_function()
# 输出 : I am a stand alone function

# 现在,你可以通过装饰器来扩展上面这个函数
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
# 输出 :
# Before the function runs
# I am a stand alone function
# After the function runs

# 或者
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
# 输出 :
# Before the function runs
# I am a stand alone function
# After the function runs

很Pythonic的调用方法

@my_shiny_new_decorator
def another_stand_alone_function():
    print("Leave me alone")


another_stand_alone_function()
# 输出 :
# Before the function runs
# Leave me alone
# After the function runs

后记

And guess what? That’s EXACTLY what decorators do!

这只是原答案的基础部分,做出了十分基础详尽的讲解。

阅读下一篇?

http://www.jianshu.com/p/5f1149145c6d

哪里翻译的不好不详尽的请随时指出。

    原文作者:Kulbear
    原文地址: https://www.jianshu.com/p/c45fd47f3b85
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞