Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redefine __and__ operator

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

like image 499
Ruggero Turra Avatar asked Apr 19 '10 15:04

Ruggero Turra


People also ask

How do you overwrite an operator in Python?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

What is __ GT __ in Python?

__gt__ (a, b) Perform “rich comparisons” between a and b. Specifically, lt(a, b) is equivalent to a < b , le(a, b) is equivalent to a <= b , eq(a, b) is equivalent to a == b , ne(a, b) is equivalent to a != b , gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b .

How does __ LT __ work in Python?

Python – __lt__ magic method Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator “<” , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class.

What is __ IADD __ in Python?

iadd() :- This function is used to assign and add the current value. This operation does “a+=b” operation.


2 Answers

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

like image 170
Ned Batchelder Avatar answered Sep 19 '22 00:09

Ned Batchelder


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

like image 43
SilentGhost Avatar answered Sep 20 '22 00:09

SilentGhost