[英]Can I require a subset of parameters in a python method?
I have a function that can take either 1 string or 4 strings:我有一个 function 可以带 1 个字符串或 4 个字符串:
def my_function(a, b, c, d, e):
I want the user to either pass in a
, or to pass in b, c, d and e
.我希望用户传入a
或传入b, c, d and e
。 I know that I can make them all default to None
, but then I need to have logic in my code that ensures that we either get only a
, or that we get values for all of b
, c
, d
and e
.我知道我可以将它们全部默认为None
,但是我需要在我的代码中包含逻辑,以确保我们要么只获得a
,要么获得所有b
、 c
、 d
和e
的值。
Is there a better way to structure this?有没有更好的方法来构建它? I really don't want to have two different methods, but that is also a possibility.我真的不想有两种不同的方法,但这也是一种可能。
Not 100% sure if this is what you're going for.不是 100% 确定这是否是您想要的。
But this could work:但这可以工作:
def my_function(*args):
if len(args) == 1:
a = args[0]
# do stuff with a
elif len(args) == 4:
(b, c, d, e) = args
# do stuff with b,c,d,e
else:
raise Exception("Expected 1 or 4 arguments: Got " + str(len(args)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.