Python 装饰器是什么
装饰器是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
应用句法装饰器
示例
上述示例可以使用带有@符号的装饰器来简化。通过在要装饰的函数前面放置@符号,可以更轻松地应用装饰器。
# 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
极客笔记