[英]Calling one of multiple inner functions from one of the outer variables function in python
Given one of those:鉴于其中之一:
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
I'm trying to call one of multiple inner functions from one of the outer variables function in python but I get this errors:我正在尝试从 python 中的外部变量 function 之一调用多个内部函数之一,但出现此错误:
result = operations(10,5,add)
=>
NameError: name 'add' is not defined
--------------------------------------------------
result = operations(10,5,"add")
=>
TypeError: 'str' object is not callable
I know i could use this solution:我知道我可以使用这个解决方案:
def add(x,y):
return x+y
def sub(x,y):
return x-y
def operations(x, y, z):
return z(x,y)
But for me it seems clearer to use nested functions.但对我来说,使用嵌套函数似乎更清楚。
I also read this: Short description of the scoping rules?我还阅读了以下内容: 范围规则的简短描述? But it didn't really helped me.但这并没有真正帮助我。
Here's what I could come up with:这是我能想到的:
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
Let's break down the code:让我们分解代码:
def add(x, y): return x + y
def sub(x, y): return x - y
# ...
This defined all of the functions we can use.这定义了我们可以使用的所有功能。 Note: I only made them one line to keep everything a bit more concise.注意:我只写了一行以使所有内容更加简洁。 This is not necessary.这不是必需的。
if z == 'add':
return add(x, y)
elif z == 'sub':
return sub(x, y)
# elif ...
These are where we parse z, and return our values.这些是我们解析 z 并返回我们的值的地方。 These can go on as far as you want.这些可以 go 随心所欲。
else:
print(f'Sorry, {z} is not a valid function.')
return
This is just a base case for when a use enters an invalid operation.这只是用户进入无效操作的基本情况。 For example, if you ran operations(2, 2, 'not_real_function')
would return Sorry, not_real_function is not a valid function.
例如,如果您运行operations(2, 2, 'not_real_function')
将返回Sorry, not_real_function is not a valid function.
. .
Your current approach unnecessarily redefines each of add
, subtract
, etc every time operations
is called , not just once when operations
is defined.您当前的方法在每次调用operations
时都不必要地重新定义add
、 subtract
等,而不仅仅是在定义operations
时重新定义一次。 If you want to isolate the individual operations to their own namespace, use a class.如果要将各个操作隔离到它们自己的命名空间,请使用 class。
class OperatorApplication:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def subtract(x, y):
return x - y
OperatorApplication.add(x, y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.