如何优雅地定义一个只需要一个且只有一个命名参数的函数?
def foo (a=None, b=None, c=None):
if a and b in None and c is None:
return something for a
if a in None and b and c is None:
return something for b
if a is None and b in None and c:
return something for c
raise ValueError("foo requires one and only one of a, b and c",a,b,c)
比
更好的东西def foo (**args):
if len(args) != 1:
raise ValueError("foo: too many or too few args",args)
arg,val = args.iteritems().next()
if arg == "a":
return something for a
if arg == "b":
return something for b
if arg == "c":
return something for c
raise ValueError("foo: unknown argument",arg,val)
另请注意,不仅第二个版本不短于第一个版本,它还可以防止像pylint这样的静态检查程序检测到可接受的参数列表。
答案 0 :(得分:2)
非常简单,您只需计算None
s:
if [a,b,c].count(None) != 2:
raise ValueError("foo requires exactly one argument among a,b and c.")
答案 1 :(得分:1)
此代码可让您轻松判断哪个参数不是无。
def foo(a=None, b=None, c=None):
paramDict = {'a': a, 'b' : b, 'c' : c}
matches = [x for x in paramDict if paramDict[x] != None]
if len(matches) != 1:
raise ValueError("foo requires one and only one of a, b and c")
else:
print("parameter %s == %s" % (matches[0], paramDict[matches[0]]))