前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python进阶|装饰器的那些事(一)

Python进阶|装饰器的那些事(一)

作者头像
罗罗攀
发布2019-10-29 17:37:01
3480
发布2019-10-29 17:37:01
举报
文章被收录于专栏:有趣的Python和你
前言

装饰器在日志、缓存等应用中有广泛使用,我们首先从之前讲解的闭包为出发点,给大家讲解装饰器的那些事。

简单的装饰器

首先我们先复习下闭包,可以看做是函数的嵌套,而且函数内部返回的是函数对象。

代码语言:javascript
复制
def nth(exponent):
    def exponent_of(base):
        return base ** exponent
    return exponent_of

square = nth(2)
cube = nth(3)
print(square(5))
print(cube(5))

# 25 5^2
# 125 5^3

这里闭包外部传入的是具有具体值的参数,如果是传入的是一个函数对象了?那就完成了一个简单的装饰器。

代码语言:javascript
复制
def decorator(func):
    def wrapper():
        print('start to decorate')
        func()
        print('start to decorate')
    return wrapper

def test():
    print('welcome to decorate')

test1 = decorator(test)
test1()
#start to decorate
#welcome to decorate
#start to decorate

这段代码中,test1变量指向了函数wrapper(),而内部函数wrapper()又调用了test()函数,因此最后打印了三段文字。

通过@语法糖,可以将上面的代码写的更简洁、更优雅:

代码语言:javascript
复制
def decorator(func):
    def wrapper():
        print('start to decorate')
        func()
        print('start to decorate')
    return wrapper

@decorator
def test():
    print('welcome to decorate')

test()
#start to decorate
#welcome to decorate
#start to decorate

这里的@decorator相当于是test1 = decorator(test)语句。

带有参数的装饰器

如果test函数中需要加入参数的话,我们就需要在wrapper函数中加入对应的参数:

代码语言:javascript
复制
def decorator(func):
    def wrapper(message):
        print('start to decorate')
        func(message)
        print('start to decorate')
    return wrapper

@decorator
def test(message):
    print(message)

test('hello world')
#start to decorate
#hello world
#start to decorate

但是新的问题来了,如果有一个新的函数也需要用到decorator()装饰器,但是他有两个参数,我们该怎么办了?

代码语言:javascript
复制
@decorator
def test2(a,b):
    print(a+b)

那这种情况下,我们就可以使用*args 和 **kwargs。

代码语言:javascript
复制
def decorator(func):
    def wrapper(*args,**kwargs):
        print('start to decorate')
        func(*args,**kwargs)
        print('start to decorate')
    return wrapper
自定义参数的装饰器

装饰器还可以自定义参数,这里需要多一层嵌套,让内部函数重复运行多次。

代码语言:javascript
复制
def repeat(num):
    def decorator(func):
        def wrapper(*args,**kwargs):
            print('start to decorate')
            for i in range(num):
                func(*args,**kwargs)
            print('start to decorate')
        return wrapper
    return decorator

@repeat(3)
def test(message):
    print(message)

test('hello world')

#start to decorate
#hello world
#hello world
#hello world
#start to decorate
有趣的现象

使用了装饰器后,有一个有趣的现象,那就是被装饰的函数的元信息被改变了。

代码语言:javascript
复制
print(test.__name__)
# wrapper

我们也可以通过@functools.wraps(func)内置的装饰器,保留原函数的元信息。

代码语言:javascript
复制
import functools

def decorator(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        print('start to decorate')
        func(*args,**kwargs)
        print('start to decorate')
    return wrapper

@decorator
def test(message):
    print(message)

print(test.__name__)
# test
总结

本文从闭包出发,讲解了装饰器的定义和使用,其实装饰器的作用就是:通过装饰器函数,可以对原函数的功能进行修改,而不去修改原函数代码。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.10.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 简单的装饰器
  • 带有参数的装饰器
  • 自定义参数的装饰器
  • 有趣的现象
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档