我目前正在构建一个应用程序,需要迭代一系列步骤,这些步骤基本上做相同的事情,只有很少的代码不同(约15行)。步骤的数量将根据项目的配置而变化,因此为每个可能的实例创建单独的函数似乎有点愚蠢。
在JavaScript中,我会这样做:
var switches = [true, true, false, true];
var holder = {
0: function() { /* do step0 */ }
1: function() { /* do step1 */ }
2: function() { /* do step2 */ }
3: function() { /* do step3 */ }
// ...etc...
}
for (var i = 0; i < switches.length; i++)
if (switches[i])
holder[i]();
有没有一种类似于Python的方法可以做到这一点?我能想到的唯一办法就是像这样:
switches = [True, True, False, True]
class Holder(object):
@staticmethod
def do_0():
# do step0
@staticmethod
def do_1():
# do step 1
# ...etc...
def __repr__(self):
return [self.do_0, self.do_1, ...]
for action in Holder:
action()
如果我的步骤数量很多,这似乎非常低效。有没有更好的方法来处理这个问题?