我想做的基本想法是:
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)
Run Code Online (Sandbox Code Playgroud)
我知道这种想法在更多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')
Run Code Online (Sandbox Code Playgroud)
但我希望在调用函数时能够清楚区别
在 Python 中应该避免类型检查(搜索“ducktyping”)。当需要时,通常应该通过isinstance对类型进行相等检查来完成,而不是像问题所示的那样。这样做的优点是对于继承情况更加灵活。
从Python 3.4开始,可以使用 stdlib 在单独的函数中编写类似字符串的分支和类似字典的分支functools.singledispatch。
所以而不是:
def aFunction(input_):
if isinstance(input_, str):
print('you gave a string-like input')
...
elif isinstance(input_, dict):
print('you gave a dict-like input')
...
Run Code Online (Sandbox Code Playgroud)
您现在可以拥有:
from functools import singledispatch
@singledispatch
def aFunction(input_):
pass
@aFunction.register(str)
def _(input_):
print("you gave a string-like input")
@aFunction.register(dict)
def _(input_):
print("you gave a dict-like input")
Run Code Online (Sandbox Code Playgroud)
在 Python 3.5+ 中,您还有另一种选择,即使用类型提示函数注释。有关该功能的更多详细信息,请阅读PEP 484 - 类型提示。这意味着上面的单个调度 泛型函数可以写成:
from functools import singledispatch
@singledispatch
def aFunction(input_):
pass
@aFunction.register
def _(input_: str):
print("you gave a string-like input")
@aFunction.register
def _(input_: dict):
print("you gave a dict-like input")
Run Code Online (Sandbox Code Playgroud)