确保用户在Python中只指定两个函数参数中的一个参数的最佳方法
在某些函数中,我有两个参数freq和frac,我不希望用户同时指定这两个参数,或者不指定任何参数。我希望他们只指定其中一个 以下是工作代码:确保用户在Python中只指定两个函数参数中的一个参数的最佳方法,python,python-3.x,function,parameter-passing,Python,Python 3.x,Function,Parameter Passing,在某些函数中,我有两个参数freq和frac,我不希望用户同时指定这两个参数,或者不指定任何参数。我希望他们只指定其中一个 以下是工作代码: 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 i
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')
你在这里做错了很多事。如果frac为False,您可以测试not frac而不是frac,您应该使用逻辑and而不是按位&,并且您应该提高这些ValueErrors,而不是返回它们:
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')
不过,一般来说,您需要从两个选项中选择一个。为什么不要求用户传递一个布尔值,如果为真则表示freq,如果为假则表示frac
死简单的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)
现在可能有更好的解决方案,但如果没有更多细节,就无法判断…Python…如果相同的参数对freq或fraq加倍,您仍然需要一个参数标志来指示第一个参数是freq还是fraq。我认为用例不是布尔值,而是一个实际值数字、字符串或列表,对于这两个值中的一个,是的,真正的用例是没有或实际的浮点值。但非常感谢您指出我在编码方面的错误,我从未停止学习细微差别。这不会节省很多行,但会使编码更具可读性。非常感谢!
__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)