成为Python砖家(4): 装饰器decorator的简单理解

第一次理解

Python 中的装饰器(decorator),是Python中一个非常强大的工具,它是一个返回函数的函数。

上面这个定义很简洁,但是没说清楚。

第二次理解

装饰器,是一个接收函数 func、返回封装后的函数 wrapper 的函数。(没懂)

第三次理解

装饰器,是一个接收函数 func、定义一个 wrapper 函数来调用 func、并且执行其他的语句(用户自行定制),然后返回这个 wrapper 函数。(还是没懂)

第四次理解

装饰器,包括定义装饰器函数,以及使用装饰器函数两部分:

  • 定义装饰器函数时,是传入普通函数 func、 定义一个调用 func 以及其他定制化内容的函数 wrapper、并把函数 wrapper 作为返回值。
  • 使用装饰器函数时,是用 @decorator_name 的形式放到普通函数func定义的上面一行,使得原本定义的函数 func, 会被 Python 解释器解释为 func = decorator_name(func)。也就是说那个纯粹的函数被“吞掉了”,用户得到的函数是那个 wrapper, 只不过 wrapper 通常会调用原本定义的函数 func。
    嗯,还是很抽象,来看具体的例子:
import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs) # 调用原始函数
        end_time = time.time()
        print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds")
        return result
    return wrapper

# 使用装饰器, 相当于 example_function = timer_decorator(example_function)
@timer_decorator
def example_function(x):
    time.sleep(x)  # 模拟一个花费一定时间的操作
    return x * 2

def hello(x):
    time.sleep(x)
    return x * 2
hello = timer_decorator(hello)

# 调用函数
result = example_function(2)
print(f"Result: {result}")

result = hello(2)
print(f"Result: {result}")

其中

@timer_decorator
def example_function(x):
    ...

相当于

def example_function(x):
    ...

example_function = timer_decorator(example_function)

上面提到的 timer_decorator是自定义的装饰器。 Python 也自带了一些装饰器,如 staticmethodclassmethod

staticmethod 装饰器

staticmethod 装饰器是 Python 自带的。把一个方法转换为静态方法。

直白理解:

class C:
    @staticmethod
    def f(arg1, arg2, argN):...

# 相当于
def f():
    ...
    
class C:
    f = staticmethod(f)

再更具体的例子:如下的C和D类,仅仅是名字差异,功能一样

def hello(name):
    print(f"hello, {name}")

class C:
    f = staticmethod(hello)

class D:
    @staticmethod
    def f(name):
        print(f"hello, {name}")

C.f("world")
D.f("python")

在这里插入图片描述

classmethod 装饰器

classmethod: 把一个方法封装成类方法。 相比于 staticmethod 装饰器, classmethod多了第一个参数 cls(或 self), 用于访问和修改类变量。

References

file:///Users/zz/Documents/pydoc-zh-cn/python-3.12.5-docs-html/library/functions.html#staticmethod

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值