重新定义 __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,即 和
的通常行为
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()
I want (a>0) && (b>0)
, but I got b, that the usual behaviour of and
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
__and__
是二元(按位)&
运算符,而不是逻辑and
运算符。由于
and
运算符是短路运算符,因此无法将其实现为函数。也就是说,如果第一个参数为 false,则根本不会计算第二个参数。如果您尝试将其实现为函数,则必须先对两个参数进行求值,然后才能调用该函数。__and__
is the binary (bitwise)&
operator, not the logicaland
operator.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.因为你无法在 Python 中重新定义关键字(这就是
and
的意思)。__add__
用于执行其他操作:because you cannot redefine a keyword (that's what
and
is) in Python.__add__
is used to do something else: