Inheriting from Python list object(type?)
Mangabasi
mangabasi at gmail.com
Wed May 23 14:22:53 EDT 2007
On May 23, 12:47 pm, "Jerry Hill" <malaclyp... at gmail.com> wrote:
> On 23 May 2007 09:58:36 -0700, Mangabasi <mangab... at gmail.com> wrote:
>
> > There must be a way to inherit from the list type without having to
> > redefine all the methods and attributes that regular lists have.
>
> Like this:
>
> class Point(list):
> def __init__(self, x, y, z = 1):
> list.__init__(self, [x, y, z])
>
> def __getattr__(self, name):
> if name == 'x': return self[0]
> if name == 'y': return self[1]
> if name == 'z': return self[2]
>
> def __setattr__(self, name, value):
> if name == 'x': self[0] = value
> if name == 'y': self[1] = value
> if name == 'z': self[2] = value
>
> Does that show you what you need?
>
> --
> Jerry
Hi Jerry,
It is very close. It worked for many operations except when I tried
>>> from numpy import array
>>> p = Point(4,5)
>>> a = array(p)
Traceback (most recent call last):
File "<input>", line 1, in ?
ValueError: invalid __array_struct__
>>> a = array([4, 5, 1])
>>>
I can define an __array__ method for this to work but I am wondering
if we can make this
behave like a real list?
Thanks for your help.
More information about the Python-list
mailing list