@add.register(float) def_(a, b): returnfloat(a + b)
Singledispatch仅支持单个参数的函数重载
多派发
python没有提供多派发的装饰器,需要导入外部的包
1
pip install multipledispatch
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from multipledispatch import dispatch
@dispatch(int,int,int) deffun(a,b,c): result = a + b +c return result @dispatch(float,float,float) deffun(a,b,c): result = float(a + b +c) return result
defwrapper(*args): key = tuple(arg.__class__ for arg in args) if key in funcs: return funcs[key](*args) else: raise TypeError('No matching function found.')