如何在Python中创建高阶函数?

PHPz
发布: 2023-09-05 19:29:05
转载
1346人浏览过

如何在python中创建高阶函数?

在Python中,将另一个函数作为参数或将函数作为输出返回的函数被称为高阶函数。让我们来看看其特性 -

  • 该函数可以存储在变量中。

  • 该函数可以作为参数传递给另一个函数。

  • 高阶函数可以以列表、哈希表等形式存储

    立即学习Python免费学习笔记(深入)”;

  • 函数可以从函数中返回。

让我们来看一些例子 −

函数作为对象

Example

的中文翻译为:

示例

在这个例子中,这些函数被视为对象。在这里,函数demo()被赋值给一个变量 -

阿里妈妈·创意中心
阿里妈妈·创意中心

阿里妈妈营销创意中心

阿里妈妈·创意中心 0
查看详情 阿里妈妈·创意中心
# Creating a function
def demo(mystr):
   return mystr.swapcase() # swapping the case

print(demo('Thisisit!'))
sample = demo
print(sample('Hello'))
登录后复制

输出

tHISISIT!
hELLO
登录后复制

将函数作为参数传递

Example

的中文翻译为:

示例

在此函数作为参数传递。 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中的装饰器

Example

的中文翻译为:

示例

在装饰器中,函数被作为参数传递给另一个函数,然后在包装函数中被调用。让我们看一个快速的例子 −

@mydecorator
def hello_decorator():
   print("This is sample text.")
登录后复制

上面也可以写成 -

def demo_decorator():
   print("This is sample text.")
hello_decorator = mydecorator (demo_decorator)
登录后复制

装饰器示例

Example

的中文翻译为:

示例

在这个例子中,我们将把装饰器作为高阶函数来工作 -

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
登录后复制

Example

的中文翻译为:

示例

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
登录后复制

应用语法装饰器

Example

的中文翻译为:

示例

可以使用带有 @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在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号