Overloading the "and" operator

F

Fredrik Bertilsson

I am trying to overload the "and" operatior, but my __and__ method is
never called. The code look like this:

class Filter:
column = ""
operator = ""
value = ""

def __init__(self, col, op, val):
self.column = col
self.operator = op
self.value = val

def toString(self):
return self.column + " " + self.operator + " " + self.value

def __and__(self, other):
print "And"
return And(self, other)


class And:
lFilter = None
rFilter = None

def __init__(self, l, r):
self.lFilter = l
self.rFilter = r

def toString(self):
return "(" + self.lFilter.toString() + ") and (" +
self.rFilter.toString() + ")"


f1 = Filter("name", "=", "Kalle")
f2 = Filter("city", "=", "LA")
andFilter = (f1 and f2)
print andFilter.toString()

What is wrong with this code? The result when I run the script is
"city = LA". The AndFilter is never created.

/Fredrik
 
R

Robert Kern

Fredrik said:
I am trying to overload the "and" operatior, but my __and__ method is
never called.

__and__ overloads the "&" operator. The "and" keyword cannot be overloaded.

--
Robert Kern
(e-mail address removed)

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
 
T

Terry Reedy

Fredrik Bertilsson said:
I am trying to overload the "and" operatior, but my __and__ method is
never called.

That is because, properly speaking, 'and' and 'or' are, in Python, in-line
flow-control keywords (related to 'if' and 'else'), and not operators.
Operators are abbreviated function calls. For binary operators, this means
evaluating both left and right operands and then calling the function,
which may hook into a special method, as you tried to do. 'And' and 'or',
on the other hand, try to avoid evaluating the right expression.

Terry J. Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top