装饰器是Python中最强大的设计模式之一。装饰器用于向已创建的对象添加新功能,而无需修改其结构。使用装饰器,您可以轻松包装另一个函数以扩展包装的函数行为,并且无需永久修改即可完成。

函数是一等对象

在 Python 中,函数被视为一等对象,即我们可以将函数存储在变量中,从函数返回函数等。

下面是一些示例,显示 Python 中有助于理解装饰器的函数。

作为对象的函数

在此示例中,函数被视为对象。在这里,函数 demo() 被分配给 变量 −



# Creating a function def demo(mystr): return mystr.swapcase() # swapping the case print(demo('Thisisit!')) sample = demo print(sample('Hello'))

输出


tHISISIT! hELLO


将函数作为参数传递

在此函数中作为参数传递。demo3() 函数调用 demo() 和 demo2() 函数作为参数。



def demo(text): return text.swapcase() def demo2(text): return text.capitalize() def demo3(func): res = func("This is it!") # Function passed as an argument print (res) # Calling demo3(demo) demo3(demo2)

输出


tHIS IS IT! This is it!


现在,让我们围绕装饰器工作

Python 中的装饰器

在装饰器中,函数作为参数进入另一个函数,然后在包装器函数中调用。让我们看一个简单的例子:

@mydecorator
def hello_decorator():
print("This is sample text.")

以上也可以写成——

def demo_decorator():
print("This is sample text.")

hello_decorator = mydecorator (demo_decorator)

装饰器示例



def demoFunc(x,y): print("Sum = ",x+y) # outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc # calling demoFunc2 = outerFunc(demoFunc) demoFunc2(10, 20)

输出


Sum = 30


应用句法装饰器

上面的示例可以使用带有@symbol的装饰器来简化。通过在我们要装饰的函数之前放置 @ 符号来简化装饰器的应用 -



# outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc @outerFunc def demoFunc(x,y): print("Sum = ",x+y) demoFunc(10,20)

输出


Sum = 30