简体   繁体   English

如何编写返回另一个函数的函数?

[英]How do I write a function that returns another function?

In Python, I'd like to write a function make_cylinder_volume(r) which returns another function.在 Python 中,我想编写一个返回另一个函数的函数make_cylinder_volume(r) That returned function should be callable with a parameter h , and return the volume of a cylinder with height h and radius r .返回的函数应该可以使用参数h调用,并返回高度为h和半径为r的圆柱体的体积。

I know how to return values from functions in Python, but how do I return another function ?我知道如何从 Python 中的函数返回,但如何返回另一个函数

Try this, using Python:试试这个,使用 Python:

import math
def make_cylinder_volume_func(r):
    def volume(h):
        return math.pi * r * r * h
    return volume

Use it like this, for example with radius=10 and height=5 :像这样使用它,例如radius=10height=5

volume_radius_10 = make_cylinder_volume_func(10)
volume_radius_10(5)
=> 1570.7963267948967

Notice that returning a function was a simple matter of defining a new function inside the function, and returning it at the end - being careful to pass the appropriate parameters for each function.请注意,返回一个函数是在函数内部定义一个新函数并在最后返回它的简单问题——注意为每个函数传递适当的参数。 FYI, the technique of returning a function from another function is known as currying .仅供参考,从另一个函数返回一个函数的技术称为柯里化。

Using lambdas, also known as anonymous functions, you can abstract out the volume function inside the make_cylinder_volume_func to a single line.使用 lambda,也称为匿名函数,您可以将make_cylinder_volume_func中的volume函数抽象为一行。 In no way different from Óscar López's answer, the solution using lambda is still in a sense 'more functional'.与 Óscar López 的回答没有什么不同,使用 lambda 的解决方案在某种意义上仍然“更实用”。

This is how you can write the accepted answer using a lambda expression:这是使用 lambda 表达式编写接受的答案的方法:

import math
def make_cylinder_volume_fun(r):
    return lambda h: math.pi * r * r * h

And then call as you'd any other curried function:然后像调用任何其他咖喱函数一样调用:

volume_radius_1 = make_cylinder_volume_fun(1)
volume_radius_1(1) 
=> 3.141592653589793

Just want to point out that you can do this with pymonad只是想指出你可以用 pymonad 做到这一点

 import pymonad 

 @pymonad.curry
 def add(a, b):
     return a + b

 add5 = add(5)
 add5(4)
 9

I know I am too late to the party, but I think you might find this solution interesting.我知道我来晚了,但我想你可能会发现这个解决方案很有趣。

from math import pi
from functools import partial

def cylinder_volume(r, h):
    return pi * r * r * h

make_cylinder_with_radius_2 = partial(cylinder_volume, 2)
make_cylinder_with_height_3 = partial(cylinder_volume, h=3)

print(cylinder_volume(2, 3))            # 37.6991118431
print(make_cylinder_with_radius_2(3))   # 37.6991118431
print(make_cylinder_with_height_3(2))   # 37.6991118431

Here is documentation about how partial works.这是有关partial工作原理的文档

Here is one massive example which covers many of single multiple argument cases in one function这是一个巨大的例子,它涵盖了一个函数中的许多单个多参数情况

def maths(var='NA'):
if var.lower() == 'add':
    def add(*args):
        return "Sum is : "+str(sum(args))
    return add
elif var.lower() == 'substract':
    def substract(a,b):
        if a>b:
            return "Difference is : "+str(a-b)
        else:
            return "Difference is : "+str(b-a)
    return substract
elif var.lower() == 'multiply':
    def multiply(*args):
        temp = 1
        for x in args:
            temp = temp*x
        return "multiplication is : "+str(temp)
    return multiply
elif var.lower() == 'divide':
    def divide(a,b):
        return "Division is : "+str(a/b)
    return divide
else:
    print("Please choose one of given operations: 'add','substract','multiply','divide'")

Here first call the maths function with the required operation and then use the returned function for the actual calculation这里首先调用需要运算的maths函数,然后使用返回的函数进行实际计算

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写返回 Python 中的字典列表的 function? - How do I write a function that returns a list of dictionaries in Python? 如何编写返回字典的 python function - How do I write a python function that returns a dictionary 如果内部调用的所有函数都为真,我如何编写一个返回真的函数,否则返回假/错误? - how do i write a function that returns true if all the functions called inside it are true, returns false/errror otherwise? 我需要编写一个 function 来返回一个数字在另一个列表中出现的次数的列表 - I need to write a function that returns a list of how may times a number occurs in another list 如何在另一个函数内部调用多次返回变量的函数? - How do I call a function which returns a variable, multiple times, while inside another function? 在 pytest 中,如何编写一个返回另一个函数的 AsyncGenerator 的夹具? - In pytest, how to write a fixture that returns another function's AsyncGenerator? 如何使用递归编写一个在Python中重复调用另一个函数的函数? - How do I use recursion to write a function that calls another function repeatedly in Python? 如何在另一个 function 中恢复 function? - How do I resue a function in another function? 如何编写读取 a.data 文件并在 python 中返回 np 数组的 function? - How do I write a function that reads a .data file and returns an np array in python? 如何编写一个 class function 并在调用 class 时立即返回一个值? - How do I write a class function that returns a value as soon as the class is called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM