简体   繁体   English

将可选的 arguments 传递给 python 中的子功能

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

Assume I'm calling a function fu() inside another function f2() .假设我在另一个 function f2()中调用 function fu() ) 。 I would like to pass to fu() some of the optional arguments.我想将一些可选的 arguments 传递给fu() Is it possible?可能吗?

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, ??? )

I'm wondering if it is possible to write the code above in a way that something like this would work:我想知道是否有可能以这样的方式编写上面的代码:

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

If a solution does not exist, maybe something similar could be achieved by using dictionaries?如果解决方案不存在,也许可以通过使用字典来实现类似的东西?

UPDATE更新

The question above was answered by @keanu in the comment to this question. @keanu 在对此问题的评论中回答了上述问题。 Here is an extended version.这是一个扩展版本。

Now I would like to pass two functions to f2() , as well as optional parameters to those.现在我想将两个函数传递给f2() ,以及它们的可选参数。 My idea was to somehow use dictionaries:我的想法是以某种方式使用字典:

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

This, however, does not work:但是,这不起作用:

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

While I would like to get虽然我想得到

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

Is there a way to do this?有没有办法做到这一点?

YAAAAAY, SEEMS TO BE WORKING:耶,似乎有效:

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 )

Not too elegant though...虽然不太优雅...

Rather than passing function as a argument, call fu function inside f2 and use **kwargs to pass arguments inside fu .与其将 function 作为参数传递,不如在f2中调用fu function 并使用**kwargsfu中传递 arguments。 See below example.请参见下面的示例。

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)

Note: only pass the function as argument if it's going to change注意:如果要更改,仅将 function 作为参数传递

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM