是否可以 return 带参数但不调用的函数?

Is it possible to return a function with parameters but without calling it?

我想要一个函数来发送其他函数(不执行它们,但将输入存储在里面)以在我的计算集群的其他节点上开始执行。第一个函数计算另一个函数的输入。

问题是 yield 在迭代开始时执行函数,但我只希望函数在我的集群的不同节点上执行它。

我创建了以下代码来解释我自己:

def calculate(a: int,b: int ,operation: str):
  print("Working...")
  if operation == 'multiply':
    return a * b
  elif operation == 'sum':
    return a+b

def calculation_sender(a: [int], b:[int], operations: [str]):
  for i in range(len(operations)):
    yield calculate(a[i],b[i], operations[i])

a = [1,2,3]
b = [1,2,3]
operations = ['sum','multiply','sum']

for calculation in calculation_sender(a, b, operations):
  print("Don't work yet!")
  print(calculation)

输出:

正在工作...
还不工作!
2
工作...
还不工作!
4
工作...
还不工作!
6

It is possible to return a function with parameters but without calling it?

  • 是的,您可以使用 functools.partial

代码:

import functools
def calculate(a: int,b: int ,operation: str):
    print("Working...")
    if operation == 'multiply':
        return functools.partial(mul,a,b)
    elif operation == 'sum':
        return functools.partial(add,a,b)

def add(a, b):
    return a + b

def mul(a, b):
    return a * b

#return a function with parameters but without calling it
print(calculate(3,5,"sum"))
#when you need to call it, just add a "()"
print(calculate(3,5,"sum")())

结果:

Working...
functools.partial(<function add at 0x000002029FD94168>, 3, 5)
Working...
8