# [Tutor] __and_ and and_

**Emile van Sebille
**
Emile van Sebille" <emile@fenx.com

*Mon, 18 Oct 1999 17:54:35 -0700*

Arne,
A little playing from where you started got me to this.
You can then write
c = a + b # to show the union
--- or ---
c = a - b # for the intersection
#-------------------
class Bool:
def __init__(self, list=[]):
self.list = list
def __add__(self, other):
list = self.list + filter(lambda x, y=self.list: x not in y,
other.list)
return Bool(list)
def __sub__(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])
print (a + b).list
print (a - b).list
#----------results
[2, 3, 10, 5, 1, 4]
[2, 3, 5]
Emile van Sebille
emile@fenx.com
-------------------
----- Original Message -----
From: Arne Mueller <a.mueller@icrf.icnet.uk>
To: tutor <tutor@python.org>
Sent: Monday, October 18, 1999 9:57 AM
Subject: [Tutor] __and_ and and_
>* 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
*>*
*>* _______________________________________________
*>* Tutor maillist - Tutor@python.org
*>* http://www.python.org/mailman/listinfo/tutor
*>*
*>*
*