从 python 中的一个外部变量函数调用多个内部函数之一

Calling one of multiple inner functions from one of the outer variables function in python

鉴于其中之一:

def operations(x, y, z):
  def add(x,y):
    return x+y
  def sub(x,y):
    return x-y
  return z(x,y)
--------------------------------------------------
def operations(x, y, z):
  if z == add:
    def add(x,y):
      return x+y
  if z == sub:
    def sub(x,y):
      return x-y
  res = z(x,y)
  return res

我试图从 python 中的外部变量函数之一调用多个内部函数之一,但我收到此错误:

result = operations(10,5,add)
=>
NameError: name 'add' is not defined
--------------------------------------------------
result = operations(10,5,"add")
=>
TypeError: 'str' object is not callable

我知道我可以使用这个解决方案:

def add(x,y):
  return x+y
def sub(x,y):
  return x-y
def operations(x, y, z):
  return z(x,y)

但对我来说,使用嵌套函数似乎更清楚。

我也看过这个: Short description of the scoping rules? 但它并没有真正帮助我。

这是我能想到的:

def operations(x, y, z: str): 
    def add(x, y): return x + y
    def sub(x, y): return x - y
    # ...
    
    if z == 'add':
        return add(x, y)

    elif z == 'sub':
        return sub(x, y)

    # elif ...
    
    else:
        print(f'Sorry, {z} is not a valid function.')
        return

让我们分解一下代码:

    def add(x, y): return x + y
    def sub(x, y): return x - y
    # ...

这定义了我们可以使用的所有功能。 注意:我只把它们写成一行是为了让一切更简洁。这不是必须的。

    if z == 'add':
        return add(x, y)

    elif z == 'sub':
        return sub(x, y)

    # elif ...

这些是我们解析 z 和 return 我们的值的地方。这些可以继续下去,只要你想。

    else:
        print(f'Sorry, {z} is not a valid function.')
        return

这只是用户输入无效操作的基本情况。 例如,如果您 运行 operations(2, 2, 'not_real_function') 将 return Sorry, not_real_function is not a valid function..

您当前的方法在每次 operations 调用时 都不必要地重新定义 addsubtract 等,而不仅仅是一次 operations 被定义。如果您想将各个操作隔离到它们自己的命名空间,请使用 class.

class OperatorApplication:
    @staticmethod
    def add(x, y):
        return x + y
    
    @staticmethod
    def subtract(x, y):
        return x - y

OperatorApplication.add(x, y)