[Tutor] RE: __and__
Arne Mueller
a.mueller@icrf.icnet.uk
Tue, 19 Oct 1999 11:56:33 +0100
Emile van Sebille wrote:
>
> 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
>
Hi Emile,
thanks for your solution. The problem is that and, or, not sounds more
natural for my problem than +, - .
In practice: I have to catinate the results of SQL queries. Say A and B
are lists of names returned by independant SQL queries then I want to
get the intersection with 'AND'
C = A and B
or the any existing name with
C = A or B
or the xor with
C = A bot B
Anyway, I'm a little disappointed because that's againsts philosophy od
object oriented programming since an object should be allowed to defined
it's complete own world.
tell me if I'm wrong,
Arne
--
Arne Mueller
Biomolecular Modelling Laboratory
Imperial Cancer Research Fund
44 Lincoln's Inn Fields
London WC2A 3PX, U.K.
phone : +44-(0)171 2693405 | fax :+44-(0)171-269-3534
email : a.mueller@icrf.icnet.uk | http://www.icnet.uk/bmm/