如何编写一个在Python中返回函数的函数? [英] How to write a function that returns a function in Python?

查看:128
本文介绍了如何编写一个在Python中返回函数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在课程的其中一个培训部分,我给了以下问题:

编写一个函数 make_multiplier(factor),它返回一个函数,该函数接受一个参数x并返回因子* x。



例如:

  f = make_multiplier(10)
f(1)
10
f(2)
20

我完全不知道该从哪里开始。我已经对所有笔记进行了整理,找不到任何有用的东西。



有人能给我一个提示或者指出我需要做的正确方向吗? / p>

解决方案

这是一个函数,它返回一个函数:

  def foo():
def bar():
返回42

返回栏

您可以这样调用它:

  foo() ()#42 
#或
baz = foo()
baz()#42

有你的提示。


In one of the training parts of my course I was given the following question:

Write a function make_multiplier(factor) that returns a function which takes an argument x and which should return factor * x.

For example:

f=make_multiplier(10)
f(1)
10
f(2)
20

I have absolutely no idea where to start with this one; I have scrummaged through all my notes and cant find anything useful.

Could someone please give me a hint or point me in the right direction of what I need to do?

解决方案

Here is a function that returns a function:

def foo():
    def bar():
        return 42

    return bar

You can call it like so:

foo()() # 42
# or
baz = foo()
baz() # 42

There's your hint.

这篇关于如何编写一个在Python中返回函数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆