分配中的Python逻辑

时间:2010-10-27 12:43:01

标签: python

鉴于secure是一个布尔值,以下语句会做什么?

特别是第一句话。

  1. protocol = secure and "https" or "http"
  2. newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())

5 个答案:

答案 0 :(得分:12)

我讨厌这个Python习语,在有人解释之前它完全不透明。在2.6或更高版本中,您将使用:

protocol = "https" if secure else "http"

答案 1 :(得分:5)

如果protocol为真,则将secure设置为“https”,否则将其设置为“http”。

在口译员中尝试:

>>> True and "https" or "http"
'https'
>>> False and "https" or "http"
'http'

答案 2 :(得分:5)

与其他语言相比,Python稍微概括了布尔运算。在添加“if”条件运算符之前(类似于C的?:三元运算符),人们有时会使用这个习语写出等效的表达式。

and被定义为返回第一个值,如果它是boolean-false,否则返回第二个值:

a and b == a if not bool(a) else b #except that a is evaluated only once

or返回其第一个值,如果它是boolean-true,则返回其第二个值:

a or b == a if bool(a) else b #except that a is evaluated only once

如果您在上述表达式中为TrueFalse插入ab,您会看到它们按照您的预期运行,但是适用于其他类型,如整数,字符串等。如果整数为零,则整数被视为false,如果它们为空,则容器(包括字符串)为false,等等。

所以protocol = secure and "https" or "http"这样做:

protocol = (secure if not secure else "https") or "http"

......这是

protocol = ((secure if not bool(secure) else "https") 
            if bool(secure if not bool(secure) else "https") else "http")

如果secure为secure if not bool(secure) else "https",则表达式True会给出“https”,否则返回(false)secure值。因此secure if not bool(secure) else "https"本身具有与secure相同的真或假,但用“https”替换布尔值为真secure的值。表达式的外部or部分相反 - 它用“http”替换boolean-false secure值,并且不触及“https”,因为它是真的。

这意味着整体表达式会这样做:

  • 如果secure为false,则表达式的计算结果为“http”
  • 如果secure为真,则表达式的计算结果为“https”

......这是其他答案所表明的结果。

第二个语句只是字符串格式化 - 它将每个字符串元组替换为%s出现的主“格式”字符串。

答案 3 :(得分:1)

第一条线被Ned很好地解开了。

第二个语句是字符串替换。每个%s都是字符串值的占位符。所以,如果值是:

protocol = "http"
get_host(request) = "localhost"
request.get_full_path() = "/home"

结果字符串为:

http://localhost/home

答案 4 :(得分:0)

在伪代码中:

protocol = (if secure then "https" else "http")
newurl = protocol + "://" + get_host(request) + request.get_full_path()