鉴于这secure
是一个布尔值,以下语句有何作用?
特别是第一个声明.
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
Ned*_*der 12
我讨厌这个Python习语,在有人解释之前它是完全不透明的.在2.6或更高版本中,您将使用:
protocol = "https" if secure else "http"
Run Code Online (Sandbox Code Playgroud)
protocol
如果secure
为true,则设置为"https" ,否则将其设置为"http".
在解释器中尝试:
>>> True and "https" or "http"
'https'
>>> False and "https" or "http"
'http'
Run Code Online (Sandbox Code Playgroud)
与其他语言相比,Python稍微概括了布尔运算.在添加"if"条件运算符之前(类似于C的?:
三元运算符),人们有时会使用这个习语写出等效的表达式.
and
定义为返回第一个值,如果它是boolean-false,否则返回第二个值:
a and b == a if not bool(a) else b #except that a is evaluated only once
Run Code Online (Sandbox Code Playgroud)
or
如果它是boolean-true,则返回其第一个值,否则返回其第二个值:
a or b == a if bool(a) else b #except that a is evaluated only once
Run Code Online (Sandbox Code Playgroud)
如果你插上True
并False
为a
和b
在上述表达式中,你会看到,他们的工作出你所期望的,但对于其他类型的工作,喜欢整数,字符串等为好.如果整数为零,则整数被视为false,如果它们为空,则容器(包括字符串)为false,依此类推.
这样protocol = secure and "https" or "http"
做:
protocol = (secure if not secure else "https") or "http"
Run Code Online (Sandbox Code Playgroud)
......是的
protocol = ((secure if not bool(secure) else "https")
if bool(secure if not bool(secure) else "https") else "http")
Run Code Online (Sandbox Code Playgroud)
secure if not bool(secure) else "https"
如果安全True
,表达式给出"https" ,否则返回(false)secure
值.因此secure if not bool(secure) else "https"
具有与其secure
本身相同的真或假,但secure
用"https" 替换布尔值.or
表达式的外部部分相反 - 它secure
用"http" 替换boolean-false 值,并且不触及"https",因为它是真的.
这意味着整个表达式执行此操作:
secure
为false,则表达式求值为"http"secure
为true,则表达式求值为"https"......这是其他答案所表明的结果.
第二个语句只是字符串格式化 - 它将每个字符串元组替换为主格式"格式"字符串%s
.
归档时间: |
|
查看次数: |
3084 次 |
最近记录: |