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

作者: 罗罗攀 | 来源:发表于2019-10-28 14:34 被阅读0次
前言

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

简单的装饰器

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

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

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

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()函数,因此最后打印了三段文字。

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

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函数中加入对应的参数:

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()装饰器,但是他有两个参数,我们该怎么办了?

@decorator
def test2(a,b):
    print(a+b)

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

def decorator(func):
    def wrapper(*args,**kwargs):
        print('start to decorate')
        func(*args,**kwargs)
        print('start to decorate')
    return wrapper
自定义参数的装饰器

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

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
有趣的现象

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

print(test.__name__)
# wrapper

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

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
总结

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

相关文章

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

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

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

    前言 上次我们讲解了装饰器的定义和使用,这节课我们再继续深入聊聊装饰器的那些事。 装饰器的嵌套 装饰器是可以嵌套的...

  • Python装饰器(Decorator)完全指南-进阶篇

    Decorator进阶指南 在[python装饰器完全指南基础篇中],我们已经知道了python中的装饰器本质上只...

  • Python装饰器-专题笔记

    学会装饰器,Python更进阶 函数作用域到闭包到装饰器讲解,及闭包和装饰器的运用。 [√] 慕课网Meshare...

  • Python中的装饰器

    本文的内容主要参考了《Python进阶》一书 装饰器(Decorators)是什么? 我理解的装饰器,主要是设计模...

  • Python 装饰器

    最近在重新在学习 Python 进阶的内容。整理一下关于装饰器(decorator)的一些知识。在解释装饰器前,先...

  • Python进阶 装饰器

    一切皆对象 原始的装饰器 使用@的装饰器 蓝本规范 带参数的装饰器 装饰器类

  • python装饰器进阶

    为什么要使用? 使用装饰器使代码变得整洁,并且能解决硬编码问题,使用起来也很方便,但是理解起来相对没那么容易,因此...

  • Python进阶(装饰器)

    note 1:Python内置的@语法就是为了简化装饰器调用。下面两图效果一样。 note 2:python的de...

  • Python进阶 - 装饰器

    函数进阶知识 函数名只是一个指向函数的变量 在python中,一切皆对象。函数名只是一个指向函数的变量,为了验证这...

网友评论

    本文标题:Python进阶|装饰器的那些事(一)

    本文链接:https://www.haomeiwen.com/subject/iahrpctx.html