图TOOL 的博客

Python装饰器详解

装饰器是Python中的一种高级特性,允许在不修改函数定义的情况下扩展函数的功能。

基本概念

装饰器实际上是一个返回函数的高阶函数,可以通过@语法糖来应用。

示例

下面是一个简单的装饰器示例:


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

        
返回主页