Ternary plus
Mark Dickinson
dickinsm at gmail.com
Wed Feb 10 03:31:43 EST 2010
On Feb 9, 6:47 pm, Martin Drautzburg <Martin.Drautzb... at 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
More information about the Python-list
mailing list