如何简化if else语句中的布尔逻辑? [英] how to simplify boolean logic in if else statement?
本文介绍了如何简化if else语句中的布尔逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 4 个变量,其中一些是 True 和 False,对于每种组合,我将不得不调用一个或几个函数.我目前正在为每个案例使用 if else 语句,我想知道是否有更好的方法来使用字典或其他东西获得相同的结果.
I have 4 variables, some of them will be True and False, and for each combinations, i will have to call one or few functions. i am currently using a if else statement for each case and i would like to know if there is a nicer way to get the same result with a dictionary or something 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)
推荐答案
一种简化方法是识别并排除重复:
One way to simplify it would be to recognise and factor out the duplication:
if self.phone:
if self.isp() == "east":
self.launchbell()
else:
self.launchtelus()
if self.cpe_ip and self.cpe_passwd:
print 'check modem...'
self.modemstatus()
if self.pppoe:
radius = sgp_radius.Radius(self.pppoe)
print 'check radius logs...'
self.data = radius.sgp()
self.radius_save()
这篇关于如何简化if else语句中的布尔逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文