擅长:python、mysql、java
<p>以下是重构代码的另一种方法:</p>
<pre><code>foo = data.get('foo')
bar = data.get('bar')
if foo:
if bar:
dofoobar()
else:
dofoo()
elif bar:
dobar()
</code></pre>
<p>不过,我不确定这是否比克里斯蒂安的回答更清晰或更易读。在</p>
<p>为了好玩,您还可以使用<code>dict</code>,布尔元组作为键,函数作为值:</p>
^{pr2}$
<p>你应该这样使用它:</p>
<pre><code>data = {'foo': 'something'}
foo = data.get('foo')
bar = data.get('bar')
def dofoobar():
print('foobar!')
def dobar():
print('bar!')
def dofoo():
print('foo!')
actions = {(True, True):dofoobar, (False, True):dobar, (True, False):dofoo}
action = actions.get((foo is not None, bar is not None))
if action:
action()
#foo!
</code></pre>