我正在编写以下形式的函数:
def fn(adict, b):
"""`adict` contains key(str): value(list). if `b` is a dict we have to
call `do_something` for pairs of lists from `adict` and `b` for
matching keys. if `b` is a list, we have to call `do_something`
for all lists in `adict` with `b` as the common second
argument.
"""
if isinstance(b, dict):
for key, value in adict.items():
do_something(value, b[key])
else:
for key, value in adict.items():
do_something(value, b)
def do_something(x, y):
"""x and y are lists"""
pass
我知道这可能不是一个好的设计 (Is it bad design to base control flow/conditionals around an object's class?)。但是写两个函数,一个将 b 作为字典,另一个作为列表,似乎太多余了。有哪些更好的选择?
请您参考如下方法:
这类问题确实有一种模式,它被命名为“多重分派(dispatch)”或“多重方法”。您可以在此处找到一个(非常简单的)示例 Python 实现 http://www.artima.com/weblogs/viewpost.jsp?thread=101605
使用此解决方案,您的代码可能如下所示:
from mm import multimethod
@multimethod(list, dict)
def itersources(sources, samples):
for key, value in sources.iteritems():
yield value, samples[key]
@multimethod(list, list)
def itersources(sources, samples):
for key, value in sources.iteritems():
yield value, samples
def fn(sources, samples):
for value1, value2 in itersources(sources, samples):
do_something_with(value1, value2)
