Python 装饰器

Python 装饰器

1. 简单的装饰器

下面是一个简单的装饰器示例,它记录被装饰函数的调用信息:

def my_decorator(func):
    """ 中层函数:接收被装饰的函数 """
    def wrapper():
         """ 内层函数:执行具体功能 """
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
def my_decorator(func):
    def wrapper(x):
        print("Something is happening before the function is called.")
        func(x)
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello(x):
    print(f"Hello!   {x}")

say_hello('xiao ming ')

# 这样更统一
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        func(*args, **kwargs)
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello(x):
    print(f"Hello!   {x}")

say_hello('xiao ming ')

带参数直接在内层函数添加

image-20240425205904317

2. 装饰器带参数

def repeat(num_times):
    def my_decorator(func):
        def wrapper(x):
            for i in range(num_times):
                print(f"Something is happening before the function is called.{i}")
                func(x)
                print(f"Something is happening after the function is called.{i}", end='\n\n')
        return wrapper
    return my_decorator
@repeat(3)
def say_hello(x):
    print(f"Hello!   {x}")

say_hello('xiao ming ')

image-20240425210254204

问题:定义一个装饰器,可以计算函数的执行时间

import time
def times(num_times):
    def decorated(func):
        def wrapper(x):
            times = 0
            for _ in range(num_times):
                start = time.time()
                ret = func(x)
                times += time.time() - start
            print(f"Average execution time over {num_times} runs: {times:.6f} seconds")
            times /= num_times
            return ret
        return wrapper
    return decorated

@times(5)
def func(n):
    cnt = 0
    for i in range(1, n+1):
        cnt += i
    return cnt
func(1000000)

image-20240425211038981

3. 类调用

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

    def __call__(self, *args, **kwargs):
        self.num_calls += 1
        print(f"Call {self.num_calls} of {self.func.__name__}")
        return self.func(*args, **kwargs)

@CountCalls
def say_hello():
    print("Hello!")
say_hello()
say_hello()
  return self.func(*args, **kwargs)

@CountCalls
def say_hello():
print(“Hello!”)
say_hello()
say_hello()


![image-20240425211803257](https://img-blog.csdnimg.cn/img_convert/481ee58543025ee56ecb85999ee96094.png)
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值