Python中的multidispatch
Date: 2019/10/25 Tags: Python
原始版本
def __add__(self, other):
if isinstance(other, Foo):
...
elif isinstance(other, Bar):
...
else:
raise NotImplementedError()
改进版本
from multipledispatch import dispatch
@dispatch(int, int)
def add(x, y):
return x + y
@dispatch(object, object)
def add(x, y):
return "%s + %s" % (x, y)
作者讨论了使用multidispatch的优点和问题