Reputation: 2379
I know Python doesn't support overloading, but I'm not sure how to do the following task in Python without resorting to different method names.
I have two methods which require different set of parameters:
def get_infobox_from_list(templates):
for template in templates:
if get_base_length(template[0]) >= 0:
return template
return None
def get_infobox(site, name):
# first try box template
infobox = get_infobox_from_list(get_templates(site, "{}/Box".format(name)))
if infobox is None:
infobox = get_infobox_from_list(get_templates(site, name))
return infobox
Both methods do similar things (they get you a template), but their parameters are different. Now I've read that Python is usually allowing this by using default arguments.
That might be helping sometimes, but the difference is, that the method either needs two parameters (site and name) or one (templates) but no other combination (like site and templates, only name, only site, name and templates or all three).
Now in Java I could simply define those two overloading methods. So if somebody is calling either one of them their parameters must match without defining to many or to few. So my question is, how should it be done in Python really.
Upvotes: 0
Views: 90
Reputation: 122052
You could try using *args
:
def get_infobox_from_list(*args):
if len(args) == 1:
return _get_infobox_from_list_template(*args)
else:
return _get_infobox_from_list_sitename(*args)
Then you can define the two similar sub-functions. But this is pretty awkward, and suggests that two separate methods with different names might be a better fit.
Upvotes: 3
Reputation: 10360
You could use a "wrapper" method (not sure what the correct terminology here is) that passes the parameters along to the correct version of the get_infobox_...
function.
def get_infobox(site=None, name=None, templates=None):
if site is not None and name is not None and templates is None:
get_infobox_from_site_and_name(site, name)
elif templates is not None and site is None and name is None:
get_infobox_from_list(templates)
else:
raise Exception # or some particular type of exception
However, I imagine there is a better way to accomplish what you want to do - I've never found a need to resort to a pattern like this in Python. I can't really suggest a better option without understanding why you want to do this in greater detail, though.
Upvotes: 2