Inheriting from Python list object(type?)
Mangabasi
mangabasi at gmail.com
Wed May 23 14:31:56 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
Somebody else emailed me another solution.
This is what he suggested:
class Point(list):
def __init__(self,x,y):
super(Point, self).__init__()
self.x = x
self.y = y
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.
More information about the Python-list
mailing list