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进阶|装饰器的那些事(一)

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