Python ignores the default values ​​of arguments supplied to a tuple in an 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 produce the same result, but the output of this program:

 () (0, 0) 

What I don’t understand here?

+5
source share
1 answer

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

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

The main reason for this is that since tuples are immutable, they must first be constructed with their data before you can even see them at the Python level. If the data was sent via __init__ , you would basically have an empty tuple at the beginning of your own __init__ , which then changed when you called super().__init__() .

+10
source

Source: https://habr.com/ru/post/1201683/


All Articles