2010-10-27 74 views
1

由于secure是一个布尔值,下列语句做了什么?赋值中的Python逻辑

尤其是第一条语句。

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

我很喜欢这条巨蟒分配招,真的很方便! :-) – 2010-10-27 12:50:45

+1

我尽量避免这个诡计。它比方便更容易混淆。 – 2010-10-27 14:10:09

回答

4

它设置为 “https” 如果secure是真实的,否则将其设置为 “HTTP”。

尝试在解释:

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

+1:“试试看”比询问更有意义。 – 2010-10-27 15:15:03

-1

在伪代码:

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

第一行是无效的Python – pillmuncher 2010-10-27 12:49:42

+0

它应该是'“https”如果安全,否则“http”' – 2010-10-27 12:55:54

+4

它是伪代码。 – yfeldblum 2010-10-27 15:00:41

12

我恨这个Python的成语,它是完全不透明的,直到有人解释它。在2.6或更高版本中,您可以使用:

protocol = "https" if secure else "http" 
+0

谢谢!我“知道”结果会是什么,但这个声明对我来说似乎很神秘,我无法得到它。 – 2010-10-27 15:27:19

4

与其他语言相比,Python将布尔操作概括了一下。在添加“if”条件操作符(类似于C的?:三元操作符)之前,人们有时会使用此习语编写相应的表达式。

and定义为返回的第一个值,如果它是布尔假,否则返回第二个值:

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

or如果是布尔真返回第一个值,否则返回第二个值:

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

如果在上述表达式TrueFalseab堵塞,你会看到,他们的工作出你所期望的,但他们适用于其他类型,如整数,字符串等。如果整数为零,则整数被视为假,如果容器(包括字符串)为空则为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 if not bool(secure) else "https"给 “HTTPS” 如果安全是True,否则返回(假)secure值。因此secure if not bool(secure) else "https"secure本身具有相同的真值或者错误,但是用“https”替换布尔值true secure的值。表达式的外部or部分做了相反的处理 - 它用“http”替换boolean-false secure值,并且不接触“https”,因为它是真的。

这意味着整个表达式做到这一点:

  • 如果secure为假,则表达式的值为“HTTP”
  • 如果secure为真,则表达式的计算结果为“https”

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

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

1

第一行被Ned回答得很好并放松。

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

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

得到的字符串将是:

http://localhost/home