Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ignores default values of arguments supplied to tuple in inherited class

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?

like image 236
AIGuy110 Avatar asked Sep 03 '14 00:09

AIGuy110


1 Answers

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__().

like image 148
Dolda2000 Avatar answered Nov 14 '22 21:11

Dolda2000