我想做的基本思想是:
def aFuncion(string = '', dicti = {}):
if len(str) > 0:
print 'you gave string as input'
if len(dicti) > 0:
print 'you gave a dict as input'
aFunction(string = 'test')
dict['test'] = test
aFunction(dicti = dict)
我知道这种想法在更多 OO 类型的语言中是可能的,但这在 python 中也可能吗?
现在我在做
def aFuncion(input):
if type(input) == str:
print 'you gave string as input'
if type(input) == dict:
print 'you gave a dict as input'
aFunction('test')
但我希望在调用函数时区别清楚
最佳答案
这种希望“在调用函数时区别清楚”的目标与该语言的设计理念并不相符。谷歌“鸭子打字”了解更多信息。函数的文档字符串应该明确接受的输入,这就是您需要做的全部。
在 python 中,当您希望输入是字符串或字典时,您只需编写代码,假设输入将是一个对象,该对象的行为以类似字符串的方式或类似 dict 的方式运行。如果输入没有,那么您可以根据需要尝试优雅地处理它,但通常您可以简单地让代码简单地弹出未处理的异常。这会将球放回主叫方的 field ,以决定如何处理这种情况,或者意识到他们正在发送错误数据。
通常应该避免类型检查,如果真的有必要,应该使用 isinstance
来完成,而不是像您所做的那样对类型进行相等性检查。这具有在继承情况下更灵活的优点。
def aFuncion(input_):
if isinstance(input_, str):
print 'you gave a string-like input'
elif isinstance(input_, dict):
print 'you gave a dict-like input'
aFunction('test')
在 python3 中,您现在有另一个使用类型提示函数注释的选项。有关该功能的更多详细信息,请阅读 PEP 484。
关于python - 如何为同一功能提供不同的输入类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9225679/