Python 赋值中的逻辑
假设 secure
是一个布尔值(也就是只有真和假两种状态),那么下面这些语句是干什么的呢?
特别是第一句。
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
第一句的意思是:如果 secure
是真(也就是安全的),那么 protocol
就会被赋值为 "https";如果 secure
是假(不安全),那么 protocol
就会被赋值为 "http"。简单来说,这句代码是根据 secure
的值来决定使用哪种协议。
第二句的意思是:它在创建一个新的网址 newurl
。这个网址的格式是 "协议://主机名+路径"。这里的协议就是第一句得到的 protocol
,主机名是通过 get_host(request)
获取的,而路径是通过 request.get_full_path()
获取的。最终,这句代码把这些部分组合成一个完整的网址。
5 个回答
如果secure
为真,就把protocol
设置为“https”;否则就设置为“http”。
可以在解释器中试试:
>>> True and "https" or "http"
'https'
>>> False and "https" or "http"
'http'
在Python中,布尔运算的处理方式比其他语言要更灵活一些。在添加了“if”条件运算符之前(类似于C语言中的?:
三元运算符),人们有时会用一种特定的写法来表达相同的意思。
and
运算符的定义是:如果第一个值是布尔假(即False),就返回第一个值;否则返回第二个值:
a and b == a if not bool(a) else b #except that a is evaluated only once
or
运算符的定义是:如果第一个值是布尔真(即True),就返回第一个值;否则返回第二个值:
a or b == a if bool(a) else b #except that a is evaluated only once
如果你把True
和False
分别放到上面的表达式中的a
和b
里,你会发现它们的结果符合你的预期。不过,这些运算不仅适用于布尔值,还适用于其他类型,比如整数、字符串等等。整数如果是零就被视为假,容器(包括字符串)如果是空的也被视为假,依此类推。
所以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 if not bool(secure) else "https"
的意思是:如果secure
是True
,就返回“https”;否则返回(假)secure
的值。所以secure if not bool(secure) else "https"
的真假性和单独的secure
是一样的,但把布尔真值的secure
替换成“https”。而外面的or
部分则相反——它把布尔假值的secure
替换成“http”,而不改变“https”,因为它是真值。
这意味着整个表达式的结果是:
- 如果
secure
是假的,那么表达式的结果是“http” - 如果
secure
是真的,那么表达式的结果是“https”
...这就是其他答案所提到的结果。
第二个语句只是字符串格式化——它会把每个字符串元组中的内容替换到主“格式”字符串中,替换的位置是每个%s
出现的地方。
我真的不喜欢这个Python的写法,完全不明白,直到有人给我解释。 在2.6版本或更高的版本中,你可以这样写:
protocol = "https" if secure else "http"