# Python Decorator 示例
# 定义一个简单的装饰器函数
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()
# 解释:
# 上面的代码中,`my_decorator` 是一个装饰器函数,它接受一个函数 `func` 作为参数,
# 并返回一个新的函数 `wrapper`。`wrapper` 函数在调用 `func` 之前和之后分别执行一些额外的操作。
# 使用 `@my_decorator` 语法糖可以很方便地将 `say_hello` 函数传递给 `my_decorator`,
# 从而使 `say_hello` 函数在调用时会先执行装饰器中的逻辑。
上一篇:python字符串处理
下一篇:python fsolve
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站