一篇文章理解Python 装饰器(Decorator)

Python 装饰器(Decorator)可以在不改变函数代码和引用方式的情况下给函数增加新的功能。

提起Python 装饰器,大家必定感觉特别神秘。其实装饰器本质上就是一个函数(func_A),它接受被装饰的函数(func_B)作为参数,并在其内部嵌套了一个函数(func_C),func_C 对被装饰的函数B进行封装(通常是在func B的前后增加一些功能),然后返回这个包装过的函数func_C。如下所示,我们看到的装饰器通常是这样的:

from functools import wraps

def func_A(func):
    @wraps(func)
    def func_C(*args,**kwargs):
        print 'do something before decoration'
        func(*args,**kwargs)
        print 'do something after decoration'
    return func_C

@func_A
def func_B():
    pass

那么这个代码里的@wrap和@func_A是什么意思呢,它们是怎么来的呢?接下来我将一步步地带大家理解。下文部分内容参考自https://www.runoob.com/w3cnote/python-func-decorators.html

1. Python中一切皆对象

在Python中,函数和类也是对象。具体体现在以下几个方面:

(1)可以赋值给一个变量;

(2)可以添加到集合对象中;

(3)可以作为参数传递给函数;

(4)可以当做函数返回值

# -*-coding:utf-8-*-
def hello(name='world'):
    return 'Hello, '+name
print hello()    # 调用该函数
# output: Hello, world

'''将函数赋值给变量'''
greet=hello    # 可将函数赋值给一个变量(注意这里没有加小括号)
print greet()    # 运行一下试试
# output: Hello, world

'''将函数添加到集合对象中'''
a_list=[]   # 定义一个集合对象
a_list.append(hello)    # 将函数添加到集合中
for item in a_list:
    print item
# output: <function hello at 0x000000000361E9E8>

'''作为参数传递给函数'''
def print_type(var):    # 定义一个带参数的函数
    print type(var)
print_type(hello)
# output: <type 'function'>

'''当做函数返回值'''
def return_a_func():
    print '返回一个函数:'
    return hello
my_hello=return_a_func()
print my_hello
# output: 返回一个函数:
# <function hello at 0x000000000331E9E8>

2. 在函数中再定义一个函数

刚才是函数的基本知识了。更进一步的,在Python中我们可以在一个函数中定义另一个函数:

def hi(name="world"):
    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

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

3. 从函数中返回函数

其实并不需要再一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:

def hi(name="world"):
    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    if name == "world":
        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 参数默认是 world,所以函数 greet 被返回了。如果我们把语句改为 a = hi(name = "ali"),那么 welcome 函数将被返回。我们还可以打印出 hi()(),这会输出 now you are in the greet() function

4. 将函数作为参数传给另一个函数

def hi():
    return "hi world!"

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 world!

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

5. 你的第一个装饰器

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

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

为了将被装饰函数的参数传递给装饰器,加入了*args和**kwargs。蓝本规范:

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接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

以上,就是Python装饰器的来源。希望能够对大家有所启发。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值