美文网首页
《Python 核心技术与实战》 学习笔记 Day16 强大的装

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

作者: _相信自己_ | 来源:发表于2023-01-30 20:17 被阅读0次

简单的装饰器


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():
    ...

相关文章

  • Python核心技术与实战笔记目录

    参考资料: 极客时间 Python核心技术与实战学习 Python核心技术与实战(极客时间)链接:http://g...

  • 2019-06-20

    “Python 实战及机器学习(深度学习)核心技术培训班” Python 是一门有条理的和强大的面向对象的程序设计...

  • 2019-06-30

    “Python 实战及机器学习(深度学习)核心技术培训班” Python 是一门有条理的和强大的面向对象的程序设计...

  • Python对象的比较和拷贝

    李文轩 2019-08-17声明:这是本人学习极客时间的Python核心技术与实战的笔记,有侵权请联系我。 ' =...

  • Python03 字符串

    以下主要是听极客时间:Python核心技术与实战时做的笔记 字符串是python一种常见的数据类型,比如函数的注释...

  • Python02 数据结构:字典和集合

    以下主要是听极客时间:Python核心技术与实战时做的笔记 对于每一门编程语言,数据结构都是重中之重。对于Pyth...

  • Python01 数据结构:列表和元组

    以下主要是听极客时间:Python核心技术与实战时做的笔记 对于每一门编程语言,数据结构都是重中之重。对于Pyth...

  • 极客时间

    我的已购专栏。 左耳听风 黄勇的OKR实战笔记 Kafka核心技术与实战 OpenResty从入门到实战 Java...

  • Redis线程那些事

    本文作为学习笔记,文章内容来自“极客时间”专栏《Redis核心技术与实战》,如有侵权,请告知,必即时删除。 Red...

  • 针对Redis内存碎片以及缓冲区溢出的优化

    本文作为学习笔记,文章内容来自“极客时间”专栏《Redis核心技术与实战》,如有侵权,请告知,必即时删除。 1、内...

网友评论

      本文标题:《Python 核心技术与实战》 学习笔记 Day16 强大的装

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