There is a function with a default value for a parameter:

def g(y, z = "default"):
    print  y, z

I want to call this function from a function "f", that among others should also contain a parameter "z", which shall be optional, i. e. the user of "f" should be able to call "f" with or without providing a value for "z". If he calls "f" without passing "z" in the argument list, "f" should call "g" so that the default value for "z" is used in the end. The value used as the default value (in this example "default") should occur only once in the code.

有帮助吗?

解决方案

It sounds like your main goal is to make sure "default" only occurs once in the code.

def g(y, z = None):
    if z is None:
        z = "default"
    print y, z

def f(y, z = None):
    g(y, z)

其他提示

Use **kwargs:

def f(**kwargs):
    g("fixed-y", **kwargs)

f() # prints "fixed-y default"
f(z='mushroom') # prints "fixed-y mushroom"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top