python中的操作重载

python中的操作重载,python,Python,我知道逻辑上和用于布尔运算,如果两个条件都为真,则计算为真,但我对以下语句有问题: 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 an

我知道逻辑上
用于布尔运算,如果两个条件都为真,则计算为真,但我对以下语句有问题:

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.

x和y
基本上是指:

返回
y
,除非
x
为False-ish-在这种情况下返回
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'

未重载


在您的代码中,
“ashish”
是一个真实值(因为非空字符串是真实的),因此它计算
“sahil”
。由于
“sahil”
也是一个真实值,
“sahil”
将返回到print语句,然后进行打印。

如果
左侧表达式的结果为falsy,则其计算结果为falsy。否则,它将计算为其右侧表达式的结果<代码>“ashish”是真实的。

您希望它打印什么?Python的逻辑运算符不返回布尔值。看一下文档:有一段时间我以为您手动键入了所有这些操作(然后我向上滚动并找到了
组合
);-)@阿什维尼乔杜里:我不敢;)然而,我可以粘贴输出,因此我不需要解释
组合
的作用,但通过这种方式,我不仅给出了答案,还提供了进一步探索的工具。即使“sahil”不是真实的,它仍然是
操作符返回的值。@mattbyant:,第二个元素总是返回,除非第一个元素被认为是false(例如,空字符串、
false
、零、空列表等)。是的,我可能应该解释一下,但我认为@chepner很好地涵盖了它。