singledispatch 是functools模块中的函数 使用@singledispatch装饰的函数会变成泛函数 #python 支持函数重载 singledispatch支持 单泛函数重载,根据第一个参数类型决定使用哪个函数 from functools import singledispatch from collections import abc @singledispatch def show(obj): print(obj,type(obj),"ibj") #参数字符串 @show.register(str) def _(str): print(str,type(str),'str') #参数int @show.register(int) def _(int): print(int,type(int),'int') @show.register(tuple) @show.register(dict) def _(text): print(text,type(text),'text') show('sgdg') show(3) show({'a':1,'b':2})
输出结果如下:
sgdg <class 'str'> str
3 <class 'int'> int
{'b': 2, 'a': 1} <class 'dict'> text