和python中的操作重载

use*_*772 5 python

我知道逻辑上and用于布尔值,如果两个条件都为真,则评估为true,但是我对以下语句有疑问:

print "ashish" and "sahil"

it prints out "sahil"?
 another example:
 return s[0] == s[-1] and checker(s[1:-1])
 (taken from recursive function for palindrome string
 checking            
please explain it and other ways and is oveloaded ,especially what the second statement do.
Run Code Online (Sandbox Code Playgroud)

Mat*_*ant 10

and 没有超载.

在你的代码中,"ashish"是一个truthy值(因为非空字符串是真的),所以它进行评估"sahil".同样"sahil"是一个truthy值,"sahil"返回到print语句然后打印.

  • 即使"sahil"不是真正的,它仍然是`和`运算符返回的值. (2认同)

Tad*_*eck 7

x and y 基本上是指:

返回y,除非x是假的 - 在这种情况下返回x

以下是可能的组合列表:

>>> from itertools import combinations
>>> items = [True, False, 0, 1, 2, '', 'yes', 'no']
>>> for a, b in combinations(items, 2):
    print '%r and %r => %r' % (a, b, a and b)


True and False => False
True and 0 => 0
True and 1 => 1
True and 2 => 2
True and '' => ''
True and 'yes' => 'yes'
True and 'no' => 'no'
False and 0 => False
False and 1 => False
False and 2 => False
False and '' => False
False and 'yes' => False
False and 'no' => False
0 and 1 => 0
0 and 2 => 0
0 and '' => 0
0 and 'yes' => 0
0 and 'no' => 0
1 and 2 => 2
1 and '' => ''
1 and 'yes' => 'yes'
1 and 'no' => 'no'
2 and '' => ''
2 and 'yes' => 'yes'
2 and 'no' => 'no'
'' and 'yes' => ''
'' and 'no' => ''
'yes' and 'no' => 'no'
Run Code Online (Sandbox Code Playgroud)