鉴于secure
是一个布尔值,以下语句会做什么?
特别是第一句话。
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
答案 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)
?:
三元运算符),人们有时会使用这个习语写出等效的表达式。
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
如果您在上述表达式中为True
和False
插入a
和b
,您会看到它们按照您的预期运行,但是适用于其他类型,如整数,字符串等。如果整数为零,则整数被视为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()