Python 中的运算符重载

5

我知道逻辑上and被用于布尔值,当且仅当两个条件都为真时才会评估为真。但是我对以下语句有疑问:

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.

3
你希望它打印什么? - alecxe
7
Python的逻辑运算符不返回布尔值。请查看文档:http://docs.python.org/3.3/library/stdtypes.html#boolean-operations-and-or-not - Blender
3个回答

10

and未被重载。

在您的代码中,"ashish"是一个真值(因为非空字符串是真值),因此它会计算"sahil"。由于"sahil"也是一个真值,所以"sahil"被返回到print语句并被打印出来。


2
即使“sahil”不是真值,它仍然是“and”运算符返回的值。 - chepner
@MattBryant:正如@chepner所说,除非第一个元素被视为假(例如空字符串,“False”,零,空列表等),否则始终返回第二个元素。 - Tadeck
是的,我可能应该解释一下,但我认为@chepner已经讲得很好了。 - Matt Bryant

7

x和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'

1
一开始我还以为你是手动输入这些操作的(后来我往上滑发现了combinations)。;-) - Ashwini Chaudhary
1
@AshwiniChaudhary: 我不敢这样做 ;) 不过我可以直接粘贴输出结果,这样我就不需要解释combinations的作用了,但是这样我不仅给了OP答案,还给了他/她进一步探索的工具。 - Tadeck

4
如果and左侧表达式的结果为假值,那么它将返回该假值。否则,它将返回右侧表达式的结果。"ashish" 是真值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接