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
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 == .
__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 .
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.
iadd() :- This function is used to assign and add the current value. This operation does “a+=b” operation.
__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.
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 (...
&
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With