重新定义__and__运算符 [英] redefine __and__ operator
本文介绍了重新定义__and__运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我不能重新定义__and__
运算符?
Why I can't redefine the __and__
operator?
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
I want (a>0) && (b>0)
, but I got b, that the usual behaviour of and
推荐答案
__and__
是二进制(按位)&
运算符,而不是逻辑and
运算符.
__and__
is the binary (bitwise) &
operator, not the logical and
operator.
由于and
运算符是短路运算符,因此无法实现为函数.也就是说,如果第一个参数为false,则根本不评估第二个参数.如果您尝试将其实现为函数,则在调用该函数之前必须先对两个参数进行求值.
Because the and
operator is a short-circuit operator, it can't be implemented as a function. That is, if the first argument is false, the second argument isn't evaluated at all. If you try to implement that as a function, both arguments have to be evaluated before the function can be invoked.
这篇关于重新定义__and__运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文