Problems with classes and __add__ and __mul__...

david_ullrich at my-deja.com david_ullrich at my-deja.com
Fri Jun 16 13:09:09 EDT 2000


In article <20000616011643.L26436 at xs4all.nl>,
  Thomas Wouters <thomas at xs4all.net> wrote:
> On Thu, Jun 15, 2000 at 10:52:31PM +0000, abg at saturnsys.com wrote:
>
> > I would like to do this...
> > def __add__(self, other_instance):
> >     return self.list + other_instance.list
>
> > Which returns a list.  I would like to return an object of my class
type, but
> > it's not right obvious to me as to how to do that.
>
> Well, the result of 'x + y' is exactly what you return in x's __add__
> method, or if x doesn't have one, what y's __radd__ returns. So, if
you want
> 'x + y' to return an instance, make __add__ return an instance:
>
> class spam:
> 	def __init__(self, l=None):
> 		self.list = l or []
>
> 	def __add__(self, other_instance):
> 		return spam(self.list + other_instance.list)
>
> If you're worried about 'spam' not being accessible to '__add__',
because
> you are defining the class outside of the global namespace, you can do
this
> as well:
>
> 	def __add__(self, other_instance):
> 		return self.__class__(self.list + other_instance.list)
>
> A bit more clutter, but possibly more obvious.

   Another advantage to doing it this way is it does the
right thing if self is an instance of a subclass of spam.
(I started returning self.__class__(whatever) from
__xxx__ methods a while ago, wasn't sure whether it
would be regarded as evil to do it that way. I guess
not; that's a relief.)

DU


Sent via Deja.com http://www.deja.com/
Before you buy.




More information about the Python-list mailing list