AIGuy110
AIGuy110

Reputation: 1425

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?

Upvotes: 5

Views: 480

Answers (1)

Dolda2000
Dolda2000

Reputation: 25855

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

Upvotes: 11

Related Questions