python新手,有這樣的情況:
myfun.py:
def fun(x, ...):
par1 = ...
par2 = ...
... # many pars
parn = ...
return #*long and complicated function of all the pars and x inputs*
有時我想修改一個或多個 pars 而不修改 myfun.py 本身。我知道我可以:
- 將每個 par 定義為fun的引數并為其賦予默認值
- 制作一個字典 par_dict = {'par1': ..., ...} 然后在我的回傳代碼中有 par1 的地方用 par_dict['par1'] 替換它。然后使用 par_dict.update() 獲取字典引數并更新我的 pars。
這些選項的任何干凈緊湊的替代品?我想要這樣的東西:
fun(x_in, par10=5)
# output uses 5 where par10 occurs in the function, in other words the argument to the function overrides the values set inside the function.
謝謝你。
uj5u.com熱心網友回復:
我發現最pythonic的方式是這樣的:首先你定義函式,比如
def fun(x, *, par1=1, par2=2, ..., parn=999):
return # function using all params
該函式具有其默認設定,以及引數的預定義值。* 作為第二個引數是為了防止將位置引數用于比 x 變數更遠的位置。
然后你可以使用可配置的字典來改變引數:
params = {
'par1': 10,
'par2': 20,
...
'parn': 0}
fun(X, **params)
**params將字典中宣告的變數分配給函式中的輸入引數。
編輯也可以使用嵌套函式,如下所示:
def outer(par1=1, par2=2, ..., parn=999):
def inner(x):
return # function using x and pars...
return inner
請注意,外部函式的引數不需要具有默認值。然后你“實體化”這個函式,將它與任何一組新引數一起使用。
params = {...} # like the previous example
fun = outer(**params)
fun(X)
您可以使用outer創建不同的函式,其行為與您輸入的引數一樣,例如:
params1 = {...}
fun1 = outer(**params1)
params2 = {...}
fun2 = outer(**params2)
a = fun1(X)
b = fun2(X)
在這種情況下, a和b是不同的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/444667.html
