7

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Ruggero Turra
  • 16,929
  • 16
  • 85
  • 141

2 Answers2

14

__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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 1
    Note that you *could* allow overloading of `and` with short circuiting by providing a more complex interface, as has been suggested for Python (http://www.python.org/dev/peps/pep-0335/), though it is not supported. – Mike Graham Apr 19 '10 at 15:55
  • Interesting, I hadn't seen that PEP. – Ned Batchelder Apr 19 '10 at 16:32
1

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 (...&...

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 2
    According to this weird distinction of keyword and operator, it shouldn't be possible to redefine `in`. But `__contains()__` is perfectly valid... – glglgl Jun 25 '13 at 16:47