我经常在 python 中使用三元运算符并且效果很好:-) 现在我已经看到在大多数情况下可以使用“或”运算符。 例如:
# Ternary operator example
class Foo:
first = 'First'
second = 'Second'
def bar(self):
return self.first if self.first else self.second
foo=Foo()
foo.bar() # returns 'First'
foo.first = None
foo.bar() # returns 'Second'
使用“或”运算符作为 Short-cirquit evaluation 可以实现相同的功能.
# Short-cirquit evaluation
class Foo:
first = 'First'
second = 'Second'
def bar(self):
return self.first or self.second
foo=Foo()
foo.bar() # returns 'First'
foo.first = None
foo.bar() # returns 'Second'
现在问题:
Short-cirquit 评估的用法是否会被视为 pep-8 和 pythonic 用法还是不够明确? 它是否被接受为专业解决方案?
最佳答案
是的,使用 or
或 and
短路是完全合理的。重要的部分是生成的代码应该是您可以制作的最具可读性和可维护性的版本。例如,当我向下抓取一个 get
引用列表时,我会做类似的事情
return obj and obj.record and obj.record.field_I_want
当引用序列中的任何内容不存在时,这很好地给我 None
,但如果一切正常,则返回字段值。
关于python - 使用快捷表达式而不是三元是pythonic吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57808543/