From: Gabriel Genellina on
En Tue, 09 Feb 2010 15:47:43 -0300, Martin Drautzburg
<Martin.Drautzburg(a)web.de> escribi�:

> Carl Banks wrote:
>
>> You can have __add__ return a closure for the first addition, then
>> perform the operation on the second one. Example (untested):
>>
>
> That's way cool.
>
> <Flash of insight> Of course! - CURRYING!! If you can return closures
> you can do everything with just single-parameter functions.</Flash of
> insight>
>
> BTW I am not really trying to add three objects, I wanted a third object
> which controls the way the addition is done. Sort of like "/" and "//"
> which are two different ways of doing division.

See http://code.activestate.com/recipes/384122/ for another cool hack that
may help with that.

--
Gabriel Genellina

From: Mark Dickinson on
On Feb 9, 6:47 pm, Martin Drautzburg <Martin.Drautzb...(a)web.de> wrote:
> BTW I am not really trying to add three objects, I wanted a third object
> which controls the way the addition is done. Sort of like "/" and "//"
> which are two different ways of doing division.

That seems like a reasonable use case for a third parameter to
__add__, though as others have pointed out the only way to pass the
third argument is to call __add__ explicitly. Here's an extract from
the decimal module:

class Decimal(object):

...

def __add__(self, other, context=None):
other = _convert_other(other)
if other is NotImplemented:
return other

if context is None:
context = getcontext()

<add 'self' and 'other' in context 'context'>

...

And here's how it's used in the decimal.Context module:

class Context(object):

...

def add(self, a, b):
"""Return the sum of the two operands.

>>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Decimal('19.00')
>>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Decimal('1.02E+4')
"""
return a.__add__(b, context=self)

--
Mark
From: Mark Dickinson on
On Feb 10, 8:31 am, Mark Dickinson <dicki...(a)gmail.com> wrote:
> And here's how it's used in the decimal.Context module:

Aargh! decimal.Context *class*, not module.

And it occurs to me that it would have been cleaner to have
Decimal.__add__ call Context.add rather than the other way around.
Then Decimal.__add__ could have stayed a two-argument function, as
<deity of your choice> intended. Oh well.

--
Mark