如何将两个或三个参数传递给函数?

时间:2022-06-20 02:09:27

This is maybe a little different than just the traditional *args **kwargs paradigm:

这可能与传统的* args ** kwargs范式有点不同:

I have a mathematical function that takes three independent parameters as input, however, it can also be solved (non-compactly) by specifying any two of the three.

我有一个数学函数,它将三个独立的参数作为输入,但是,它也可以通过指定三个中的任何两个来解决(非紧凑)。

Currently, I have the non-compact solution based strictly on a and b, with c as an optional constraint:

目前,我有一个严格基于a和b的非紧凑解决方案,c作为可选约束:

def func(a,b,c=None):
  if c is not None:
    # do something with a, b, and c
  else:
    # do something with only a, b
  return result

However, I would like to be able to specify any two of a, b, or c, and still keep the option of specifying all three. What's the most Pythonic way of doing that?

但是,我希望能够指定a,b或c中的任意两个,并且仍然保留指定所有三个的选项。最恐怖的做法是什么?

2 个解决方案

#1


3  

You can just give them all default values of None, then pass the arguments as keyword arguments:

你可以给它们所有默认值None,然后将参数作为关键字参数传递:

def foo(a=None, b=None, c=None):
    print(a, b, c)

foo(a=123, b=456)
foo(a=123, c=789)
foo(b=456, c=789)

This example produces:

这个例子产生:

123 456 None
123 None 789
None 456 789

#2


0  

Alternative approach:

def func(**kwargs):
    p_keys = kwargs.keys()
    if 'a' in p_keys and 'b' in p_keys:
        # non-compact solution
        if 'c' in p_keys:
            # apply optional constraint
    elif set(p_keys).issubset({'a', 'b', 'c'}):
        # apply solution for 'any two'
    else:
        #complain loudly
        pass
    return

#1


3  

You can just give them all default values of None, then pass the arguments as keyword arguments:

你可以给它们所有默认值None,然后将参数作为关键字参数传递:

def foo(a=None, b=None, c=None):
    print(a, b, c)

foo(a=123, b=456)
foo(a=123, c=789)
foo(b=456, c=789)

This example produces:

这个例子产生:

123 456 None
123 None 789
None 456 789

#2


0  

Alternative approach:

def func(**kwargs):
    p_keys = kwargs.keys()
    if 'a' in p_keys and 'b' in p_keys:
        # non-compact solution
        if 'c' in p_keys:
            # apply optional constraint
    elif set(p_keys).issubset({'a', 'b', 'c'}):
        # apply solution for 'any two'
    else:
        #complain loudly
        pass
    return