Python 函数如果传递了另一个参数则强制参数

Python function make parameter mandatory if another parameter is passed

我在 Python 中有一个函数

def myfunc(a, b=None, c=None):
    my code here

有没有办法确保如果用户传递参数b的值就需要传递参数cmyfunc

您可以在函数中编写一个简单的 if 条件。请看下面的代码:

def myfunc(a, b=None, c=None):
    if c is not None and b is None:
        raise ValueError("Value of b must be passed if value of c is passed")
    your code here

没有任何内置方式。自己查一下:

def myfunc(a, b=None, c=None):
    if b is not None and c is None:
        raise ValueError("Invalid arguments")
    # ...