使用快捷表达式而不是三元是pythonic吗?

Is it pythonic to use shortcut expression instead of ternary?

我经常在 python 中使用三元运算符,效果很好:-) 现在我已经看到在大多数情况下可以使用 'or' 运算符。 例如:

# 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'

使用 'or'-运算符作为 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 的使用还是不够明确? 它是否被接受为专业解决方案?

是的,使用 orand 短路是完全合理的。重要的部分是生成的代码应该是您可以制作的最具可读性和可维护性的版本。例如,当我向下爬取 get 个引用列表时,我会做类似

的事情
return obj and obj.record and obj.record.field_I_want

当参考序列中的任何内容不存在时,这很好地给我 None,但如果一切正常,则 returns 字段值。