
在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!
现在,让我们讨论装饰器。我们可以使用装饰器作为高阶函数。
在装饰器中,函数被作为参数传递给另一个函数,然后在包装函数中被调用。让我们看一个快速的例子 −
@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
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
以上就是如何在Python中创建高阶函数?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号