我想在概念上实现以下内容:
if condition1:
action1()
also if condition2:
action2()
also if condition3:
action3()
also if condition4:
action4()
also if condition5:
action5()
also if condition6:
action6()
else:
print("None of the conditions was met.")
实现这样的逻辑的合理而明确的方法是什么?怎么可能将else绑定到多个if语句?我是否会被迫创建一个布尔来跟踪事物?
解决方法:
好的,根据澄清,这样的事情会很好:
class Accumulator(object):
none = None
def also(self, condition):
self.none = not condition and (self.none is None or self.none)
return condition
acc = Accumulator()
also = acc.also
if also(condition1):
action1()
if also(condition2):
action2()
if also(condition3):
action3()
if also(condition4):
action4()
if acc.none:
print "none passed"
您可以扩展它以获取有关if语句执行的其他信息:
class Accumulator(object):
all = True
any = False
none = None
total = 0
passed = 0
failed = 0
def also(self, condition):
self.all = self.all and condition
self.any = self.any or condition
self.none = not condition and (self.none is None or self.none)
self.total += 1
self.passed += 1 if condition else self.failed += 1
return condition
标签:python,if-statement,series
来源: https://codeday.me/bug/20190711/1435270.html