Python之装饰器

1.认识装饰器

在python中,对于一个函数,若想在其运行前后做点什么,那么装饰器是再好不过的选择,话不多说,上代码。

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 01.py	
__author__ = 'howie'	
from functools import wraps	
def decorator(func):	
    @wraps(func)	
    def wrapper(*args, **kwargs):	
        print("%s was called" % func.__name__)	
        func(*args, **kwargs)	
    return wrapper	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello()
outputs:	
hello was called	
Hello howie!

这段代码,初看之下,确实不是很理解,接下来一步一步分析,看看装饰器到底是怎么工作的。

2.装饰器原理

在python中,方法允许作为参数传递,想在某个函数执行前后加点料,也可以这样简单实现。

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-1.py	
__author__ = 'howie'	
def decorator(func):	
    print("%s was called" % func.__name__)	
    func()	
def hello(name="howie"):	
    print("Hello %s!" % name)	
decorator(hello)

由此,上面代码也可以这样写:

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-2.py	
__author__ = 'howie'	
def decorator(func):	
    print("%s was called" % func.__name__)	
    func()	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello

两段代码执行后:

outputs:	
hello was called	
Hello howie!

表面上看来, 02-2.py代码看起来也可以很好地执行啊,可请注意,在末尾处, hello只是函数名称,它并不能被调用,若执行 hello(),就会报 TypeError:'NoneType'objectisnotcallable对象不能调用错误,这是自然,在 decorator中 func()直接将传入的函数实例化了,有人会想,那如果这样改呢?

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-3.py	
__author__ = 'howie'	
def decorator(func):	
    print("%s was called" % func.__name__)	
    return func	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello()

确实,这样改是可以,可有没有想过,若想在函数执行结束后加点装饰呢?这样便行不通了,可能又有人会想,若这样改呢?

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-4.py	
__author__ = 'howie'	
def decorator(func):	
    print("%s was called" % func.__name__)	
    func()	
    return bye	
def bye():	
    print("bye~")	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello()

这样写看起来,恩,怎么说呢,总有种没有意义的感觉,不如直接将在外部的函数放进 decorator中,如下:

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-5.py	
__author__ = 'howie'	
def decorator(func):	
    def wrapper():	
      print("%s was called" % func.__name__)	
      func()	
      print("bye~")	
    return wrapper	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello()

执行:

outputs:	
hello was called	
Hello howie!	
bye~

怎么样,输出的结果是不是符合要求,其实简单来看的话,可以这样理解 hello()==decorator(hello)()==wrapper(),最后其实就是执行 wrapper()函数而已,事实就是如此的简单,不妨来验证一下:

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-6.py	
__author__ = 'howie'	
def decorator(func):	
    def wrapper():	
      print("%s was called" % func.__name__)	
      func()	
      print("bye~")	
    return wrapper	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello()	
print(hello.__name__)
outputs:	
hello was called	
Hello howie!	
bye~	
wrapper

果然就是执行了wrapper函数,解决问题的同时也会出现新的问题,那便是代码中本来定义的hello函数岂不是被wrapper函数覆盖了,又该如何解决这个问题呢?这时候 functions.wraps就可以登场了,代码如下:

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 02-7.py	
__author__ = 'howie'	
from functools import wraps	
def decorator(func):	
    @wraps(func)	
    def wrapper():	
      print("%s was called" % func.__name__)	
      func()	
      print("bye~")	
    return wrapper	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello()	
print(hello.__name__)

执行代码:

outputs:	
hello was called	
Hello howie!	
bye~	
hello

functions.wraps作用是不是一目了然哈~到了这一步,再看01.py的代码,是不是代码结构清晰明了,只不过多了个参数~

#!/usr/bin/env	
# -*-coding:utf-8-*-	
# script: 01.py	
__author__ = 'howie'	
from functools import wraps	
def decorator(func):	
    @wraps(func)	
    def wrapper(*args, **kwargs):	
        print("%s was called" % func.__name__)	
        func(*args, **kwargs)	
    return wrapper	
@decorator	
def hello(name="howie"):	
    print("Hello %s!" % name)	
hello('world')

猜都猜得到执行后输出什么了。

3.结语

只要了解装饰器原理,不管是带参数的装饰器,还是装饰器类,都是小菜一碟。 若有错误,尽请指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值