Override __and__ statement

Why can't I override the statement __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()

I want (a>0) && (b>0), but I got b that normal behaviorand

+5
source share
2 answers

__and__is a binary (bitwise) operator &, not a logical operator and.

Since the operator andis a short circuit operator, it cannot be implemented as a function. That is, if the first argument is false, the second argument is not evaluated at all. If you try to implement this as a function, both arguments must be evaluated before the function is called.

+10
source

(, and) Python. __add__ - :

(... &...

+1

All Articles