python基础 – functools.singledispatch
代码基于python 3.5.2
python3.0以后functools.singledispath装饰器,学名:单分派泛函数,名字有点晦涩。分析后得出,该装饰器主要实现的功能就是:根据传入参数类型的不同而进行不同的函数处理。
举例说明:
from functools import singledispath
import number
@singledispatch
def show(obj):
print (obj, type(obj), "obj")
@show.register(numbers.Integral) #numbers.Integral 是 int 的虚拟超类
def _(n):
print (n, type(n), "int")
@show.register(dict)
def _(dict):
print (dict, type(dict), "dict")
if __name__ == __main__:
show(2)
show({'a':1})
输出结果:
2 <class 'int'> int
{'a': 1} <class 'dict'> dict
上述代码可以得知,调用show()函数时,会先对传入实参的类型进行判断,然后根据类型分配给各个具体函数。类似于java中的重载