Python装饰器初探:理解和使用装饰器
装饰器是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()
在这个例子中,my_decorator
是一个装饰器,它接收一个函数作为参数,并返回一个新的函数。当我们在say_hello
函数前加上@my_decorator
时,实际上是将say_hello
函数传递给my_decorator
来处理。
还没有评论,来说两句吧...