Problems subclassing tuple instead of list

Don Garrett garrett at bgb.cc
Sat Feb 8 20:22:14 EST 2003


   I'm running Python 2.2.2, and having trouble creating a subclass of 
tuple. I don't understand exactly what the problem is. I've attached a 
few code fragments that explain my confusion.

   My best guess so far is that the problem is occuring the tuple 
types's meta type. But I haven't yet found any documentation for it. I 
can subclass list with no issues, but I really wanted to create a 
read-only constant list, with some additional attributes. It seems to 
make more since to extend the type tuple, instead of trying to dump down 
list.


# This was my first attempt, it doesn't work
class TuplePlus(tuple):
     def __init__(self, *elements):
         tuple.__init__(self, elements)

t = TuplePlus(1, 2)

Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "c:/DOCUME~1/garrett/LOCALS~1/Temp/python-964PUH", line 6, in ?
     t = TuplePlus(1, 2)
TypeError: tuple() takes at most 1 argument (2 given)


#   This was my second attempt. It creates an instance of TuplePlus that
# acts exactly like the tuple: (1, 2)
class TuplePlus(tuple):
     def __init__(self, *elements):
         tuple.__init__(self, elements)

t = TuplePlus([1, 2])

#   This was my third attempt. It again produces the following errors.
class TuplePlus(tuple):
     def __init__(self, *elements):
         tuple.__init__(self, [elements])

t = TuplePlus(1, 2)

Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "c:/DOCUME~1/garrett/LOCALS~1/Temp/python-10044gV", line 7, in ?
     t = TuplePlus(1, 2)
TypeError: tuple() takes at most 1 argument (2 given)

-- 
Don Garrett                             http://www.bgb.cc/garrett/
BGB Consulting                                      garrett at bgb.cc





More information about the Python-list mailing list