[Tutor] Operators on complex numbers, and applying real to a list of real and complex numbers
Kent Johnson
kent37 at tds.net
Fri Sep 19 13:34:40 CEST 2008
On Fri, Sep 19, 2008 at 5:43 AM, Stephen McInerney
<spmcinerney at hotmail.com> wrote:
> Two questions about complex numbers:
>
> a) why are methods __add__,__mul__ defined but not the
> operators '+','-','*','/' ?
This is true of all the numeric types. The method that implements +
for a type is called __add__. Similarly * is implemented by __mul__.
There are many more "special" methods that implement not only numeric
operations but also things like indexing and iteration. A complete
list of methods for numeric types is here:
http://docs.python.org/ref/numeric-types.html
> How can I bind the methods to the obvious operators (without creating a
> custom
> subclass of complex?) It seems pretty weird writing a.__add__(b)
No need, this is done by the Python runtime. It converts a+b into
a.__add__(b). (More or less...it could also end up as b.__radd__(a) or
raise TypeError.)
> b) Say I have a list ll which mixes real (float) and complex numbers.
> ll = [1, 0.80-0.58j, 0.11+.2j]
> What is the best Python idiom for getting the list of real parts of elements
> of ll?
> [lx.real for lx in ll] fails because only complex numbers have a 'real'
> attribute, real numbers don't (slightly bizarre).
> Unless I write the not-so-readable:
> [(type(lx) is complex and lx.real or lx) for lx in ll]
> or define my own function.
You could also use getattr(lx, 'real', lx) if you prefer.
> Do any of you see a need for a math.real() (or math.complex())
> function, which operates on all numeric types?
> Then I could simply take the list comprehension
> [real(lx) for lx in ll]
> Is this worthy of a PEP?
> It seems simple but overlooked.
I guess someone agrees with you, at least in spirit...In Python 2.6
and 3.0, numeric types are in a hierarchy and integers and floats are
also complex:
In [13]: (5).real
Out[13]: 5
In [18]: (5).imag
Out[18]: 0
(The parentheses are needed to avoid a syntax error.)
Also
In [20]: import numbers
In [21]: isinstance(5, numbers.Complex)
Out[21]: True
In [22]: isinstance(5.0, numbers.Complex)
Out[22]: True
More information about the Tutor
mailing list