Calling parent constructor with different argument list

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Aug 14 20:15:52 EDT 2009


En Fri, 14 Aug 2009 19:24:26 -0300, pinkisntwell <pinkisntwell at gmail.com>  
escribió:

> class Vertex(tuple):
>     pass
>
> class Positioned_Vertex(Vertex):
>
>     def __init__(self, a, b):
>         Vertex.__init__(a)
>
> a=Positioned_Vertex((0,0,0), 1)
>
> This gives:
>
> TypeError: tuple() takes at most 1 argument (2 given)
>
> It looks like the explicit call to Vertex.__init__ is never made and
> Vertex.__init__ is implicitly called when a Positioned_Vertex is
> created. Is there a way to work around this and call the constructor
> with the intended argument list?

The tuple constructor (like numbers, strings, and other immutable objects)  
never calls __init__. You have to override __new__ instead:

py> class Point3D(tuple):
...   def __new__(cls, x, y, z):
...     obj = super(Point3D, cls).__new__(cls, (x,y,z))
...     return obj
...
py> a = Point3D(10, 20, 30)
py> a
(10, 20, 30)
py> type(a)
<class '__main__.Point3D'>

See http://docs.python.org/reference/datamodel.html#basic-customization

-- 
Gabriel Genellina




More information about the Python-list mailing list