Inheriting from Python list object(type?)

Mangabasi mangabasi at gmail.com
Wed May 23 14:54:42 EDT 2007


On May 23, 1:43 pm, "Jerry Hill" <malaclyp... at gmail.com> wrote:
> On 23 May 2007 11:31:56 -0700, Mangabasi <mangab... at gmail.com> wrote:
>
> > When I modified this to:
>
> > class Point(list):
> >     def __init__(self,x,y):
> >         super(Point, self).__init__([x, y])
> >         self.x = x
> >         self.y = y
>
> > It worked.
>
> Are you sure?
>
> >>> p = Point(10, 20)
> >>> p
> [10, 20]
> >>> p.x
> 10
> >>> p.x = 15
> >>> p
> [10, 20]
> >>> p[0]
> 10
> >>> p.x
> 15
>
> That doesn't look like what you were asking for in the original post.
> I'm afraid I don't know anything about numpy arrays or what special
> attributes an object may need to be put into a numpy array though.
>
> --
> Jerry

You are right.  I did not include the whole story in my last post.
This is the real code I used and so far it worked.  I am still testing
it though.  Toes and fingers crossed!

class Point(list):
    def __init__(self, x, y, z = 1):
        super(Point, self).__init__([x, y, z])
        self.x = x
        self.y = y
        self.z = 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

Thanks for the correction.




More information about the Python-list mailing list