Python中的装饰器是如何工作的?
在Python中,装饰器(Decorator)是一种特殊类型的函数,它可以在不修改原函数代码的情况下,为原函数添加新的功能或者改变其行为。
装饰器的工作原理是:
创建一个装饰器函数,该函数通常接受一个或多个要被装饰的函数作为参数。
在装饰器函数中,添加额外的行为。例如,你可能会在内部调用另一个函数,然后返回被装饰的原始函数。
当你想给某个函数添加装饰时,只需将这个函数作为参数传递给你的装饰器函数即可。
举个例子:
# 装饰器
def my_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
# 原始函数
@my_decorator
def say_hello():
print("Hello!")
say_hello()
输出结果:
Before the function is called.
Hello!
After the function is called.
还没有评论,来说两句吧...