redefine __and__ operator

旧街凉风 提交于 2019-12-10 15:01:52

问题


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


回答1:


__and__ is the binary (bitwise) & operator, not the logical and 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.




回答2:


because you cannot redefine a keyword (that's what and is) in Python. __add__ is used to do something else:

These methods are called to implement the binary arithmetic operations (...&...



来源:https://stackoverflow.com/questions/2668667/redefine-and-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!