“和”和“或”组合在一个语句中时如何工作?

新手上路,请多包涵

出于某种原因,这个功能让我感到困惑:

 def protocol(port):
    return port == "443" and "https://" or "http://"

有人可以解释幕后发生的事情的顺序以使这项工作按原样进行吗?

在我尝试之前,我是这样理解的:

要么 A)

 def protocol(port):
    if port == "443":
        if bool("https://"):
            return True
    elif bool("http://"):
        return True
    return False

或 B)

 def protocol(port):
    if port == "443":
        return True + "https://"
    else:
        return True + "http://"

这是 Python 中的某种特殊情况,还是我完全误解了语句的工作原理?

原文由 orokusaki 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 330
2 个回答

这是一个古老的成语;插入括号以显示优先级,

 (port == "443" and "https://") or "http://"

x and y returns y if x is truish, x if x is falsish; a or b ,反之亦然,返回 a 如果它是真实的,否则 b

因此,如果 port == "443" 为真,则返回 and 的 RHS,即 "https://" 。否则, and 为假,因此 or 发挥作用并返回“http://”, 它的 RHS。

在现代 Python 中,翻译这个古老习语的更好方法是:

 "https://" if port == "443" else "http://"

原文由 Alex Martelli 发布,翻译遵循 CC BY-SA 2.5 许可协议

and 如果左操作数为真,则返回右操作数。 or 如果左操作数为假,则返回右操作数。否则它们都返回左操作数。他们据说 合并

原文由 Ignacio Vazquez-Abrams 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题