July 17, 2006
Python中的and和or
Python 中的逻辑运算,and 和 or 并不是像c/c++类的语言一样,返回 true或者 false。他们的返回值(return value)是两个操作符(operantor)中,其中一个的值。
这个特点似乎在同是脚本语言的lua中也是一样。有人还认为这不太正常,有点气愤。
实际上这种设计还是很合乎逻辑的,也有用处。比如以前我曾经不解类似c语言中 condition?a:b 这种语句在python中的写法,在水木上得到指教,用 and 和 or 就可以很简洁地表达出来。
r = cond and x or y
Python 2.4文档的 5.10 中也提到了:
Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or ‘foo’ yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not ‘foo’ yields False, not ”.
举的例子是:“如果为空(非法值、失败)的话就使用默认值”,简洁的表达。
所以这里的 x and y 可以理解为:先x,“然后再” y。是不是让 and 这个词回归本来的语义了呢?
同理,x or y就是:如果x 不成的话,y (为真)也行啊。
如果上面的 x, y 都是函数的话,x or y or z… 就是 “从左到右执行这些操作,直到其中一个成功为止” 。 x and y and z… 就是“从左到右执行这些操作,有一个失败就拉倒”。
如果 and 和 or 组合起来,意思就更丰富了。
这不正是脚本语言所追求的吗? 不能从c/c++的角度来理解脚本语言。
Filed by
charlie
at 9:06 pm under Python
2 Comments


