Setting the default value of a function input to equal another input in Python

后端 未结 3 1617
天涯浪人
天涯浪人 2021-02-05 07:13

Consider the following function, which does not work in Python, but I will use to explain what I need to do.

def exampleFunction(a, b, c = a):
    ...function bo         


        
3条回答
  •  鱼传尺愫
    2021-02-05 07:46

    This general pattern is probably the best and most readable:

    def exampleFunction(a, b, c = None):
        if c is None:
            c = a
        ...
    

    You have to be careful that None is not a valid state for c.

    If you want to support 'None' values, you can do something like this:

    def example(a, b, *args, **kwargs):
        if 'c' in kwargs:
            c = kwargs['c']
        elif len(args) > 0:
            c = args[0]
        else:
            c = a
    

提交回复
热议问题