I need to implement a two parameters function with python. The parameter types can be: (String, String), (String, List) or (List, List). In Java I would use overloading to manage this situation but in python I just can think in the next solution:
def myFunction(param1, param2):
if isinstance(param1, basestring) and isinstance(param2, basestring):
# implementation 1
elif isinstance(param1, basestring) and isinstance(param2, list):
# implementation 2
elif ...
else:
raise TypeError
Is this the best way to do it? I am new in python.
Thanks.
Duck typing means testing for methods, not using isinstance()
. What do you intend to do with the input?
If, for example, you'll accept a string, then split that string on newlines and use it otherwise like a list, test for .splitlines()
:
if hasattr(arg1, 'splitlines'):
arg1 = arg1.splitlines()
if hasattr(arg2, 'splitlines'):
arg2 = arg2.splitlines()
# now arg1 and arg2 are presumed to be lists.
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.