subclassing tuple

Jason Orendorff jason at jorendorff.com
Mon Feb 11 07:57:27 CET 2002


damien morton wrote:
> class triple(tuple):
>     def __init__(self, x, y, z):
>         tuple.__init__(self, (x,y,z))
> 
> >>> t = triple(1,2,3)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: tuple() takes at most 1 argument (3 given)
> 
> For some reason, subclasses of tuple dont call the proper __init__ code.

The magic __new__() method is called to create the object.
[The __init__() method is then called, but you might not need it.]

  class triple(tuple):
      def __new__(cls, x, y, z):
          return tuple.__new__(cls, (x, y, z))

More: http://www.python.org/2.2/descrintro.html

## Jason Orendorff    http://www.jorendorff.com/






More information about the Python-list mailing list