【问题标题】:Python function make parameter mandatory if another parameter is passed如果传递了另一个参数,则 Python 函数使参数成为强制性参数
【发布时间】:2021-11-02 06:09:49
【问题描述】:

我在 Python 中有一个函数

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

有没有办法确保如果用户传递参数b的值,就必须将参数c传递给myfunc

【问题讨论】:

    标签: python user-defined-functions


    【解决方案1】:

    您可以在函数中编写一个简单的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
    

    【讨论】:

    • 如果用户提供了None 作为第三个参数,这将失败
    • 这里的假设是传递None 等价于不传递任何东西,因为None 是这里的默认值。
    • None 被假定为默认值,不是没有值被传递
    【解决方案2】:

    不是以任何内置方式。自己检查一下:

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

    【讨论】:

    • 如果用户提供了None 作为第三个参数,这将失败
    • @sahasrara62 如果您提供与默认值相同的值,则假定您想要默认值所暗示的任何行为。
    • 这可能是在 None 中传递 c 值的情况之一,从这个意义上说,至少这个解决方案没有任何意义
    • @sahasrara62 对于定义为def func(a=None) 的python 函数,使用func()func(None)func(a=None) 调用它都应该具有相同的行为。
    猜你喜欢
    • 2019-03-05
    • 2017-08-07
    • 2018-11-29
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2019-10-09
    相关资源
    最近更新 更多