I have a function that can take either 1 string or 4 strings:
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
. 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
.
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.
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)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.