簡體   English   中英

將可選的 arguments 傳遞給 python 中的子功能

[英]Passing optional arguments to sub-function in python

假設我在另一個 function f2()中調用 function fu() ) 。 我想將一些可選的 arguments 傳遞給fu() 可能嗎?

def f0( arg1, arg2 = None):
    print( arg1 )
    if arg2 is not None:
        print( f'arg2 of f0() is: {arg2}' )

def f1( arg1, arg2 = None, arg3 = None ):
    print( arg1 )
    if arg2 is not None:
        print( f'arg2 of f1() is: {arg2}' )
    if arg3 is not None:
        print( f'arg3 of f1() is: {arg3}' )

def f2( fu, arg1, *args, **kwargs ):
    fu( arg1, ??? )

我想知道是否有可能以這樣的方式編寫上面的代碼:

f2(f0, 1)
> 1

f2(f0, 1, 2)
> 1
> arg2 of f0() is: 2

f2(f0, 1, 2, 3)
> Error

f2(f1, 1)
> 1

f2(f1, 1, 2)
> 1
> arg2 of f1() is: 2

f2(f1, 1, 2, 3)
> 1
> arg2 of f1() is: 2
> arg3 of f1() is: 3

???
> 1
> arg3 of f1() is: 2

如果解決方案不存在,也許可以通過使用字典來實現類似的東西?

更新

@keanu 在對此問題的評論中回答了上述問題。 這是一個擴展版本。

現在我想將兩個函數傳遞給f2() ,以及它們的可選參數。 我的想法是以某種方式使用字典:

def f2( fu0, fu1, arg10, arg11, f0_args = None, f1_args = None ):
    fu0( arg10, f0_args )
    fu1( arg11, f1_args )

但是,這不起作用:

f2( f0, f1, 1, 2, f1_args = { 'arg3' : 4 } )
> 1
> 2
> arg2 of f1() is: {'arg3': 4}

雖然我想得到

> 1
> 2
> arg3 of f1() is: 4

有沒有辦法做到這一點?

耶,似乎有效:

def f2( fu0, fu1, arg10, arg11, f0_args = None, f1_args = None ):
    if f0_args is None:
        fu0( arg10 )
    else:
        fu0( arg10, **f0_args )
    if f1_args is None:
        fu1( arg11 )
    else:
        fu1( arg11, **f1_args )

雖然不太優雅...

與其將 function 作為參數傳遞,不如在f2中調用fu function 並使用**kwargsfu中傳遞 arguments。 請參見下面的示例。

def fu(a=5, b=7, c=3):
    return a*b*c

def f2(**kwargs):
    x = fu(**kwargs)
    return x

y = f2(a=4, b=3)
print(y)

注意:如果要更改,僅將 function 作為參數傳遞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM