<p>你在你的问题中暗示了某种逻辑的查找表可能是一种方法,你可以用很多方法来做类似的事情。在</p>
<p>一种方法是,如你所说,使用dict,如下所示。在</p>
<p>对于您的特定示例,这种方法会产生比好看的“简化并消除重复”解决方案更复杂的代码,但是这种方法更容易扩展到对于不同情况有更多不同逻辑的情况。。。我不是说“更好”。。。只是一个不同的选择!在</p>
<pre><code>def launch_isp_portal_and_radius():
print "launch ISP portal, modem and radius"
# etc
# etc
DecisionTable = {
# cpe_ip cpe_passwd phone ppoe
(True, True, True, True ) : launch_isp_portal_and_radius,
(True, True, False, False) : launch_modem_test_only,
(False, False, True, False) : only_Bell_portal,
(False, True, True, False) : only_Bell_portal,
(True, False, True, False) : only_Bell_portal,
(True, True, False, True ) : launch_modem_and_radius_test,
(False, False, False, False) : only_radius_tests,
(False, True, False, False) : only_radius_tests,
(True, False, False, False) : only_radius_tests,
(False, False, True, True ) : bell_and_radius_tests
(False, True, True, True ) : bell_and_radius_tests,
(True, False, True, True ) : bell_and_radius_tests,
(True, True, True, False) : launch_modem_and_bell_tests
}
action = DecisionTable.get((self.cpe_ip, self.cpe_passwd, self.phone, self.ppoe))
if action:
action()
else:
raise StandardError("Whoa, internal logic error!")
</code></pre>
<p>(当然,还有其他方法可以生成决策表—数组是另一个明显的选择。数组的问题是使它的静态声明看起来对它所代表的逻辑是可读的…)</p>
<p>(编辑:按照jons的建议,将dict索引到tuple上)</p>