《Python 核心技术与实战》 学习笔记 Day16 强大的装饰器

简单的装饰器


def my_decorator(func):
    def wrapper():
        print('wrapper of decorator')
        func()
    return wrapper

def greet():
    print('hello world')

greet = my_decorator(greet)
greet()

# 输出
wrapper of decorator
hello world

这里的函数 my_decorator() 就是一个装饰器,它把真正需要执行的函数 greet() 包裹在其中,并且改变了它的行为,但是原函数 greet() 不变。

带有参数的装饰器

一个简单的办法,是可以在对应的装饰器函数 wrapper() 上,加上相应的参数,比如:


def my_decorator(func):
    def wrapper(message):
        print('wrapper of decorator')
        func(message)
    return wrapper


@my_decorator
def greet(message):
    print(message)


greet('hello world')

# 输出
wrapper of decorator
hello world

带有自定义参数的装饰器

装饰器可以接受原函数任意类型和数量的参数,除此之外,它还可以接受自己定义的参数。


def repeat(num):
    def my_decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(num):
                print('wrapper of decorator')
                func(*args, **kwargs)
        return wrapper
    return my_decorator


@repeat(4)
def greet(message):
    print(message)

greet('hello world')

# 输出:
wrapper of decorator
hello world
wrapper of decorator
hello world
wrapper of decorator
hello world
wrapper of decorator
hello world

类装饰器

类也可以作为装饰器。类装饰器主要依赖于函数call(),每当你调用一个类的示例时,函数call()就会被执行一次。


class Count:
    def __init__(self, func):
        self.func = func
        self.num_calls = 0

    def __call__(self, *args, **kwargs):
        self.num_calls += 1
        print('num of calls is: {}'.format(self.num_calls))
        return self.func(*args, **kwargs)

@Count
def example():
    print("hello world")

example()

# 输出
num of calls is: 1
hello world

example()

# 输出
num of calls is: 2
hello world

...

装饰器的嵌套

实际上,Python 也支持多个装饰器,比如写成下面这样的形式:


@decorator1
@decorator2
@decorator3
def func():
    ...
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、函数的核心点 在聊装饰器之前,我们先“约法三章”,如果这“三章”都不承认,那我们的装饰器也就没得聊了,哪三章呢...
    LiuShiYi阅读 311评论 0 0
  • 在讲解装饰器在接口自动化测试项目的应用之前,我们先来介绍一下python装饰器到底是个什么 装饰器 说装饰器就不得...
    测试轩阅读 319评论 0 1
  • 首先一句话,所谓的装饰器,其实就是通过装饰器函数,来修改原函数的一些功能,使得原函数不需要修改。 函数核心回顾 p...
    D_w阅读 518评论 11 7
  • 目录链接:https://www.jianshu.com/p/e1e201bea601 函数核心 一、在 Pyth...
    leacoder阅读 243评论 0 1
  • 在python中,函数也是对象,我们可以把函数作为另外一个函数的返回值(也就是闭包),也可以在函数里面嵌套函数。如...
    倔犟的贝壳阅读 243评论 0 0