我终于弄懂了Python的装饰器(一)

此系列文档:python

1. 我终于弄懂了Python的装饰器(一)设计模式

2. 我终于弄懂了Python的装饰器(二)api

3. 我终于弄懂了Python的装饰器(三)app

4. 我终于弄懂了Python的装饰器(四)函数

1、装饰器基础(什么是装饰器)

Python的函数是对象

要了解装饰器,您必须首先了解函数是Python中的对象。这具备重要的联系。post

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

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 NameError as e:
    print(e)
    #输出: "name 'shout' is not defined"

print(scream())
# 输出: 'Yes!'复制代码

请记住这一点,咱们将在不久后回头再说。设计

Python函数的另外一个有趣特性是能够在另外一个函数中定义它们!code

def talk():

    # 您能够在“talk”中动态定义一个函数...
    def whisper(word="yes"):
        return word.lower()+"..."

    # ...而且能够立马使用它。
    print(whisper())

#您每次调用“talk”,都会定义“whisper”,而后在“talk”中调用“whisper”。

talk()
# 输出: 
# "yes..."

# 可是"whisper"不存在"talk"定义之外的地方:

try:
    print(whisper())
except NameError as e:
    print(e)
    #输出 : "name 'whisper' is not defined"复制代码

函数参考

OK,应该还在看吧?如今开始有趣的部分...对象

您已经看到函数是对象。 所以,函数:

  • 能够分配给变量
  • 能够在另外一个函数中定义

这意味着一个函数能够return另外一个功能

def getTalk(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 = getTalk()      

#您能够看到“talk”是一个函数对象:
print(talk)
#输出 : <function shout at 0xb7ea817c>

#函数对象返回的内容:
print(talk())
#输出 : Yes!

#若是您感到困惑,甚至能够直接使用它:
print(getTalk("whisper")())
#outputs : yes...复制代码

还有更多的内容!

若是能够return一个函数,则能够将其中一个做为参数传递:

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

doSomethingBefore(scream)
#输出: 
#I do something before then I call the function you gave me
#Yes!复制代码

好吧,您只具有了解装饰器所需的全部信息。 您会看到,装饰器是“包装器(wrappers)”,这意味着它们使您能够在装饰函数以前和以后执行代码,而无需修改函数自己的代码内容。

手工进行装饰

您将知道如何进行手动操做:

#装饰器是讲另一个函数做为参数的函数
def my_shiny_new_decorator(a_function_to_decorate):

    # 在内部,装饰器动态定义一个函数:包装器(wrappers)。
    # 此功能将被包装在原始功能的外部,以便它能够在代码以前和以后执行代码。
    def the_wrapper_around_the_original_function():

        # 在调用原始函数以前,将要执行的代码放在此处
        print("Before the function runs")

        #在此处调用函数(使用括号)
        a_function_to_decorate()

        # 在调用原始函数后,将要执行的代码放在此处
        print("After the function runs")

    #至此,“a_function_to_decorate”从未执行过。
    #咱们返回刚刚建立的包装函数。
    #包装器包含函数和在代码以前和以后执行的代码。随时可使用!
    return the_wrapper_around_the_original_function

#如今,假设您建立了函数,可是不想再修改的函数。
def a_stand_alone_function():
    print("I am a stand alone function, don't you dare modify me")

a_stand_alone_function() 
#输出: I am a stand alone function, don't you dare modify me

#因此,您能够装饰它以扩展其行为。
#只需将其传递给装饰器,它将动态地包装在
#您想要的任何代码中,并为您返回准备使用的新功能:

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, don't you dare modify me
#After the function runs复制代码

如今,您可能但愿每次调用a_stand_alone_functiona_stand_alone_function_decorated都调用它。 这很简单,只需a_stand_alone_function用如下方法返回的函数覆盖my_shiny_new_decorator

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, don't you dare modify me
#After the function runs

#这正是装饰器的工做!复制代码

装饰器神秘化

这里展现一下使用装饰器的语法:

@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复制代码

是的,仅此而已。@decorator只是实现如下目的的捷径:

another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)复制代码

装饰器只是装饰器设计模式的pythonic变体。 Python中嵌入了几种经典的设计模式来简化开发(例如迭代器)。

固然,您能够累加装饰器:

def bread(func):
    def wrapper():
        print("</''''''\>")
        func()
        print("<\______/>")
    return wrapper

def ingredients(func):
    def wrapper():
        print("#tomatoes#")
        func()
        print("~salad~")
    return wrapper

def sandwich(food="--ham--"):
    print(food)

sandwich()
#输出: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#输出:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>复制代码

使用Python装饰器语法:

@bread
@ingredients
def sandwich(food="--ham--"):
    print(food)

sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>复制代码

您设置装饰器事项的顺序是很重要的,如::

@ingredients
@bread
def strange_sandwich(food="--ham--"):
    print(food)

strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~复制代码

本文首发于BigYoung小站

相关文章
相关标签/搜索