[Tutor] __and_ and and_
Arne Mueller
a.mueller@icrf.icnet.uk
Mon, 18 Oct 1999 17:57:18 +0100
Hi All,
I've a problem with redefining the 'and' operator for a specific class.
Here's some code that does not work:
class Bool:
def __init__(self, list=[]):
self.list = list
def __and__(self, other):
list = filter(lambda x, y=self.list: x in y, other.list)
return Bool(list)
b = Bool([1, 2, 3, 4, 5])
a = Bool([2, 3, 10, 5])
c = a and b
print c.list
[1, 2, 3, 4, 5]
The expected result is:
[2, 3, 5]
The following class definition works as expected:
class Bool:
def __init__(self, list=[]):
self.list = list
def and_(self, other):
list = filter(lambda x, y=self.list: x in y, other.list)
return Bool(list)
b = Bool([1, 2, 3, 4, 5])
a = Bool([2, 3, 10, 5])
c = a.and_(b)
print c.list
[2, 3, 5]
Why doesn't the 'in-operator' '__and__' behave the same way as 'and_'?
It'd be much better object oriented desgin to say:
c = a and b
instead
c = a.and_(b) # ugly :-(
Any explanations or better any solutions?
thank you very much for your help,
Arne