Problems with classes and __add__ and __mul__...

Thomas Wouters thomas at xs4all.net
Thu Jun 15 19:16:43 EDT 2000


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.

> Or, would it be better to do this?  (spam is the class here...)

[ Other options here]

> Thanks for any help that you can give me.  It would be great if you emailed
> your responses to a_gurno at yahoo.com as I don't always get to check this group
> as often as I would like. Adam

The best thing to do would probably be to subclass the standard UserList :-)
This already emulates all list-like operations, like +/*, .append(),
.extend(), etcetera. You can simply subclass it to add your own
functionality. See the 'UserList' module.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list