重定义 __and__ 运算符
为什么我不能重新定义 __and__
运算符?
class Cut(object):
def __init__(self, cut):
self.cut = cut
def __and__(self, other):
return Cut("(" + self.cut + ") && (" + other.cut + ")")
a = Cut("a>0")
b = Cut("b>0")
c = a and b
print c.cut()
我想要的是 (a>0) && (b>0)
,但是我得到了 b,这就是 and
的正常行为。
2 个回答
1
因为在Python中,你不能重新定义一个关键字(and
就是一个关键字)。而__add__
是用来做其他事情的:
14
__and__
是二进制(按位)&
运算符,而不是逻辑 and
运算符。
因为 and
运算符是一个短路运算符,所以它不能被实现为一个函数。也就是说,如果第一个参数是假的,第二个参数根本不会被计算。如果你试图把它实现成一个函数,那么在调用这个函数之前,两个参数都必须被计算。