我正在嘗試將一個函式作為另一個函式中的變數運行,但是第一個函式有一個僅在第二個函式中指定的變數。我不認為這是一個好的做法,但我想我是在角落里給自己編程的。
def in_func(n, p):
print(p)
print(f'Num {n}')
def out_func(func):
n = 0
while n < 10:
func(n)
n = 1
p = 8
out_func(in_func(n, p))
解決此類問題的最佳做法或解決方案是什么?
uj5u.com熱心網友回復:
您正在呼叫 in_func并將結果傳遞給out_func. 相反,您可以例如定義一個在當前范圍內使用時lambda僅接受n引數的函式...p
p = 8
out_func(lambda n: in_func(n, p))
...或使用functools.partial相同的效果:
from functools import partial
p = 8
out_func(partial(in_func, p=p))
uj5u.com熱心網友回復:
作為引數n傳遞時不需要使用:in_func
def in_func(n):
print(f'Num {n}')
def out_func(func):
n = 0
while n < 10:
func(n)
n = 1
out_func(in_func)
編輯
假裝更新的語法可以作業并且做一些有意義的事情(必須調整才能運行它),我想你唯一的選擇是n全域宣告變數。然后in_func從自身回傳以被呼叫out_func:
def in_func(n, p):
print(p)
print(f'Num {n}')
return in_func
def out_func(func):
global n
n = 0
while n < 10:
func(n, p)
n = 1
n = 10
p = 8
out_func(in_func(n, p))
最后,也許它們不需要是同一個變數?
def in_func(n, p):
print(p)
print(f'Num {n}')
return in_func
def out_func(func):
n_b = 0
while n_b < 10:
func(n_b, p)
n_b = 1
n_a = 10
p = 8
out_func(in_func(n_a, p))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515931.html
上一篇:XSLT:從多個節點填充字串-->特定節點和節點數量可能會有所不同。如何處理?
下一篇:每個列對的Pandas總和列
