简体   繁体   中英

Python default values for parameters in delegated function calls

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, ie 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.

Use **kwargs :

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

f() # prints "fixed-y default"
f(z='mushroom') # prints "fixed-y mushroom"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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