Inheriting from Python list object(type?)
irstas at gmail.com
irstas at gmail.com
Thu May 24 05:05:04 EDT 2007
On May 23, 10:07 pm, Mangabasi <mangab... at gmail.com> wrote:
> This is the winner:
>
> 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]
> elif name == 'y':
> return self[1]
> elif name == 'z':
> return self[2]
> else:
> return self.__dict__[name]
>
> def __setattr__(self, name, value):
> if name == 'x':
> self[0] = value
> elif name == 'y':
> self[1] = value
> elif name == 'z':
> self[2] = value
> else:
> self.__dict__[name] = value
Inheritation is an "is a" relation. Point, however, is not a list.
This adds some weird behaviour to Point:
p = Point(1,2,3)
p.append(4)
print p[3]
That makes no sense but your Point implementation allows it. This
is probably even more surprasing behaviour:
p = Point(1,2,3) + Point(4,5,6)
print p
One might expect the points to be added to Point(5,7,9), not
into a list containing [1,2,3,4,5,6].
I'd suggest you don't inherit Point from anything, and just add
an __iter__ member function that iterates through x,y and z. E.g.
def __iter__(self):
yield self.x
yield self.y
yield self.z
Then you can convert a Point p to a list by doing list(p). Or to
a tuple with tuple(p). __array__ could also be implemented for
convenince with numpy (if I understood that correctly).
More information about the Python-list
mailing list