# 示例代码:使用 @ 作为装饰器
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()
# 解释说明:
# 在 Python 中,@ 符号用于定义装饰器。装饰器本质上是一个函数,它接受另一个函数作为参数,并扩展其功能而不改变原函数的定义。
# 上面的例子中,`my_decorator` 是一个装饰器函数,`say_hello` 是被装饰的函数。
# 使用 @my_decorator 语法糖可以更简洁地将 `say_hello` 函数传递给 `my_decorator`,并用返回的新函数替换 `say_hello`。
# 运行结果会先打印装饰器中的前置操作,然后执行原函数的内容,最后打印装饰器中的后置操作。
上一篇:python 调用c++
下一篇:python快速编程入门
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站