[英]relay multiple keyword arguments from outer function to inner functions in 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 中的外部變量 function 之一調用多個內部函數之一,但出現此錯誤:
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)
但對我來說,使用嵌套函數似乎更清楚。
我還閱讀了以下內容: 范圍規則的簡短描述? 但這並沒有真正幫助我。
這是我能想到的:
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 並返回我們的值的地方。 這些可以 go 隨心所欲。
else:
print(f'Sorry, {z} is not a valid function.')
return
這只是用戶進入無效操作的基本情況。 例如,如果您運行operations(2, 2, 'not_real_function')
將返回Sorry, not_real_function is not a valid function.
.
您當前的方法在每次調用operations
時都不必要地重新定義add
、 subtract
等,而不僅僅是在定義operations
時重新定義一次。 如果要將各個操作隔離到它們自己的命名空間,請使用 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.