我有4个变量,其中一些是真的和假的,对于每个组合,我必须调用一个或几个函数。 我目前正在为每种情况使用if-else语句,我想知道是否有更好的方法使用字典或其他工具来获得相同的结果。在
谢谢你
这是我的代码:
if (self.cpe_ip and self.cpe_passwd) and self.phone and self.pppoe:
print "launch ISP portal, modem and radius"
if self.isp() == "east":
self.launchbell()
else:
self.launchtelus()
print 'check modem...'
self.modemstatus()
radius = sgp_radius.Radius(self.pppoe)
print 'check radius logs...'
self.data = radius.sgp()
self.radius_save()
#exit(0)
elif (self.cpe_ip and self.cpe_passwd) and not self.phone and not self.pppoe:
print "launch modem test only"
self.modemstatus()
#exit(0)
elif not(self.cpe_ip and self.cpe_passwd) and self.phone and not self.pppoe:
#print "only Bell portal"
if self.isp() == "east":
self.launchbell()
else:
self.launchtelus()
elif (self.cpe_ip and self.cpe_passwd) and not self.phone and self.pppoe:
#print "launch modem and radius test."
self.modemstatus()
radius = sgp_radius.Radius(self.pppoe)
print 'check radius logs...'
self.data = radius.sgp()
self.radius_save()
elif not(self.cpe_ip and self.cpe_passwd) and not self.phone and self.pppoe:
#print "only radius tests."
radius = sgp_radius.Radius(self.pppoe)
self.data = radius.sgp()
self.radius_save()
elif not(self.cpe_ip and self.cpe_passwd) and self.phone and self.pppoe:
print "bell and radius tests."
if self.isp() == "east":
self.launchbell()
else:
self.launchtelus()
radius = sgp_radius.Radius(self.pppoe)
print 'check radius logs...'
self.data = radius.sgp()
self.radius_save()
elif (self.cpe_ip and self.cpe_passwd) and self.phone and not self.pppoe:
#print "launch modem and bell tests."
if self.isp() == "east":
self.launchbell()
else:
self.launchtelus()
self.modemstatus()
else:
#print "test bell only"
#launchbell(self.phone)
exit(0)
简化它的一种方法是识别和排除重复:
你在你的问题中暗示了某种逻辑的查找表可能是一种方法,你可以用很多方法来做类似的事情。在
一种方法是,如你所说,使用dict,如下所示。在
对于您的特定示例,这种方法会产生比好看的“简化并消除重复”解决方案更复杂的代码,但是这种方法更容易扩展到对于不同情况有更多不同逻辑的情况。。。我不是说“更好”。。。只是一个不同的选择!在
(当然,还有其他方法可以生成决策表—数组是另一个明显的选择。数组的问题是使它的静态声明看起来对它所代表的逻辑是可读的…)
(编辑:按照jons的建议,将dict索引到tuple上)
相关问题 更多 >
编程相关推荐