5

Here is some code to demonstrate what I'm talking about.

class Foo(tuple):
   def __init__(self, initialValue=(0,0)):
      super(tuple, self).__init__(initialValue)

print Foo()
print Foo((0, 0))

I would expect both expressions to yield the exact same result, but the output of this program is:

()
(0, 0) 

What am I not understanding here?

user2864740
  • 60,010
  • 15
  • 145
  • 220
AIGuy110
  • 1,025
  • 1
  • 10
  • 11
  • 1
    I believe [this answer](http://stackoverflow.com/questions/3120562/python-subclassing-immutable-types) might be illuminating. – Amadan Sep 03 '14 at 00:44

1 Answers1

11

That's because the tuple type does not care about the arguments to __init__, but only about those to __new__. This will make it work:

class Bar(tuple):
    @staticmethod
    def __new__(cls, initialValue=(0,0)):
        return tuple.__new__(cls, initialValue)

The basic reason for this is that, since tuples are immutable, they need to be pre-constructed with their data before you can even see them at the Python level. If the data were supplied via __init__, you would basically have an empty tuple at the start of your own __init__ which then changed when you called super().__init__().

Dolda2000
  • 25,216
  • 4
  • 51
  • 92