繁体   English   中英

确保用户指定Python中两个函数参数中的一个和仅一个的最佳方法

[英]Best way to ensure user to specify one and only one of the two function parameters in Python

some_function ,我有两个参数freqfrac ,我不希望用户同时指定它们,或者都不指定。 我希望他们仅指定其中之一。

这是工作代码:

def some_function(freq=False, frac=False):
    if (freq is False) & (frac is False):
        return (str(ValueError)+': Both freq and frac are not specified')
    elif (freq is not False) & (frac is not False):
        return (str(ValueError)+': Both freq and frac are specified')
    elif (freq is not False) & (frac is False):
        try:
            print ('Do something')
        except Exception as e:
            print (e)
    elif (freq is False) & (frac is not False):
        try: 
            print ('Do something else')
        except Exception as e:
            print (e)
    else: return (str(ValueError)+': Undetermined error')

是否有更好且更少冗长的实践来用Python表达这一点?

您可以在if语句之前使用assert 您输入的类型不清楚; 通常,如果我知道这不是有效的输入,我将使用“ None

def some_function(freq=None, frac=None):

    freq_flag = freq is not None
    frac_flag = frac is not None

    assert freq_flag + frac_flag == 1, "Specify exactly one of freq or frac"

    if freq_flag:
        print('Do something')

    elif frac_flag:
        print('Do something else')

您在这里做错了很多。 您可以测试not frac而不是frac is False ,应该使用逻辑and不是按位& ,并且应该引发那些ValueError ,而不返回它们:

def some_function(freq=False, frac=False):
    if not freq and not frac:
        raise ValueError('Both freq and frac are not specified')
    elif freq and frac:
       raise ValueError('Both freq and frac are specified')
    elif freq:      
        print ('Do something')
    else:
        print ('Do something else')

通常,您正在寻找两个选项之一。 为什么不要求用户传递一个布尔值,如果True则表示freq ,如果False则表示frac呢?

def some_function(freq):
    if freq: 
        print ('Do something')
    else:
        print ('Do something else')

无效的简单pythonic解决方案:使用两个不同的函数(它们最终可能只是真正的一个门面):

__all__ = ["freqfunc", "fracfunc"]

# private implementation
def _somefunc(freq=False, frac=False):
   # your code here

def freqfunc(freq):
    return _somefunc(freq=freq)

def fraqfunc(frac):
    return _somefunc(frac=frac)

现在可能会有更好的解决方案,但是如果没有更多细节就无法分辨...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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