Python 将应用于另一个变量的函数

Python function which will be applied to another variable

例如:

def some_function(a):
     if a == 1:
          return x ** 2
     else:
          return x - 1000

some_function(a)(b)

作为结果,当我们有 a==1 时,获得 b**2 并且在所有其他情况下 b-1000

是否有可能在 python 中得到一些未知变量,如 return,将被另一个变量替换?

问题就是不接触b,函数直接访问不到

应该有效的代码是some_function(a)(b)

这通常称为 curryingpartial 函数。在 python

中看起来像这样
from functools import partial

def some_function(a, x):
    if a == 1:
        return x ** 2
    else:
        return x - 1000

一般来说,你存储偏函数

a = 1
func = partial(some_function, a)
func(5)

但您也可以将它们作为一个衬垫使用。

partial(some_function, 1)(5)
partial(some_function, 0)(1500)

或者,您可以 some_function return 函数

def some_function(a):
    if a == 1:
        return lambda b: b **2
    else:
        return lambda b: b - 1000

使用 partial 通常是更灵活的方法。

在这种情况下,其他答案是正确的,但可能不适合您的尝试。

您尝试做的是 return 函数,Python 非常简单:

def some_function(a):
    if a == 1:
        def f(x):
            return x ** 2
    else:
        def f(x):
            return x - 1000
    return f

>>> some_function(1)(5)
25
>>> some_function(0)(1500)
500

尽管 Brian 的答案有效,但它存在代码重复并且无法利用函数闭包。

函数闭包意味着函数定义范围内的变量在创建函数后仍会保留,即使变量现在超出范围也是如此。

def some_function(a):
    def f(x):
        if a == 1:
            return x ** 2
        else:
            return x - 1000
    return f

some_function(a)(b)

>>> some_function(1)(4)
16
>>> some_function(0)(1000)
0

在这个实例中,变量a只定义在some_function的范围内,但是因为我们在f(x)中使用它,所以当我们调用返回的时候它仍然可用稍后运行。

其他答案也可以,但您可能正在寻找这个。

def first_function(a):
    return a ** 2

def second_function(a):
    return a - 1000

def some_funtion(a):
    if a == 1:
        return first_function
    else:
        return second_function

print(some_function(1)(3)) #prints 9
print(some_function(0)(1500)) #prints 500