在Python中,装饰器是一种特殊类型的函数,可以用来修改其他函数的行为。要在def
命令中使用装饰器,请按照以下步骤操作:
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
装饰器修饰。当调用say_hello
时,实际上是在调用my_decorator(say_hello)
。
say_hello()
这将输出以下内容:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
这就是如何在Python的def
命令中使用装饰器。