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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top