[英]How implement a python function with different parameter types
I need to implement a two parameters function with python. 我需要用python实现一个两个参数函数。 The parameter types can be: (String, String), (String, List) or (List, List).
参数类型可以是:(String,String),(String,List)或(List,List)。 In Java I would use overloading to manage this situation but in python I just can think in the next solution:
在Java中我会使用重载来管理这种情况但是在python中我只能在下一个解决方案中思考:
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.
我是python的新手。
Thanks. 谢谢。
Duck typing means testing for methods, not using isinstance()
. 鸭子打字意味着测试方法,而不是使用
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()
: 例如,如果您接受一个字符串,那么将该字符串拆分为换行符并使用它,就像列表一样,测试
.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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.