Is it correct this way to inherit from a list?

Jason Swails jason.swails at gmail.com
Sun Mar 3 15:40:48 EST 2013


On Sun, Mar 3, 2013 at 9:21 AM, Colin J. Williams <cjw at ncf.ca> wrote:

> On 02/03/2013 9:30 PM, gialloporpora wrote:
>
>> Risposta al messaggio di Rick Johnson :
>>
>>  What are you trying to achieve exactly?
>>>
>>
>>
>> I would like to implement a class (vector) to works with vectors, for
>> example using scalar multiplication:
>> a*v = [a*v1, a*vn]
>> and a dual class for dual vector (the only method that I'll change is
>> the __str__ method to print it as colun.
>> Sandro
>>
> Numpy facilitates this sort of thing more efficiently than using a List.
>

As a couple people have already pointed out, numpy is the way to go for
most scientific applications.  You have also been given good advice
regarding 'properly' inheriting from 'list' by calling the list.__init__
function.

The only thing I'll add here is that you can inherit from array.array
instead of list if you want a 'truly' numeric-vector without introducing
numpy as a dependency.  The advantage array.array has over list in this
instance is that it is type-restrictive for member data (it has to be
pre-declared and throws TypeError if you try to pass it a bad variable
type).

You can then proceed to override the __add__, __sub__, __mul__, and __div__
methods (and the in-place versions of these operators) to mimic vector
operations.  (By default, __add__ appends the rhs to the lhs and returns a
copy of that for array.array and list).

You can avoid all this work, however, and just use numpy.ndarray instead ;).

Good luck,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130303/3fb28a52/attachment.html>


More information about the Python-list mailing list