Subclassing complex with computed arguments
Nick Coghlan
ncoghlan at email.com
Sat Nov 27 07:43:09 EST 2004
<resend, since my newsreader had an argument with the newsserver. Kent's latest
post already addressed some of my points below>
Kent Johnson wrote:
> I don't know if there is an easy way around this. A brute force approach
> might be to override __add__(), etc to return point objects instead of
> complex -
Yup, this is the only way I know to prevent ordinary complex() objects leaking
through the interface.
> though I haven't been able to figure out how to do this. I tried:
> def __add__(self, *args, **kwds):
> val = complex.__add__(self, *args, **kwds)
> return point(val)
Try something like:
def __add__(self, other):
c_self, c_other = coerce(self, other)
val = c_self.__add__(c_other)
return point(val)
Since:
>>> x = 1
>>> c = 1j
>>> c.__add__(x)
NotImplemented
>>> c2, x2 = coerce(c, x)
>>> c2.__add__(x2)
(1+1j)
Don't forget to override the __radd__ operators and friends, too.
> class point(object):
>
> I tried adding a delegating __coerce__() to class point but it is never
> called...
new-style classes do not invoke coercion unless you explicitly call coerce() on
them. If you don't inherit from object, the __coerce__ method should get called
if it's needed.
Here's some essential reading if you want to play with numerical operators:
http://www.python.org/doc/2.3.4/ref/numeric-types.html
http://www.python.org/doc/2.3.4/ref/coercion-rules.html
(I found these two pages of the Language Reference Manual essential while
helping out with the decimal implementation for Python 2.4 - much that had been
mysterious suddenly became clear after I read these docs)
Cheers,
Nick.
More information about the Python-list
mailing list