3

Why doesn't the following work:

class CTest(tuple):
    def __init__(self,arg):
        if type(arg) is tuple:
            super(CTest,self).__init__((2,2))
        else:
            super(CTest,self).__init__(arg)
a=CTest((1,1))
print a

The ouput is (1,1), while I expect to see (2,2).

Also, why do I get a deprecation warning that object.init() takes no parameters? What should I do instead?

Óscar López
  • 232,561
  • 37
  • 312
  • 386

1 Answers1

5

Tuples are immutable, you have to override __new__:

class CTest(tuple):
    def __new__(cls, arg):
        if type(arg) is tuple:
            return super(CTest, cls).__new__(cls, (2, 2))
        else:
            return super(CTest, cls).__new__(cls, arg)

Now this works as expected:

a = CTest((1,1))
print a
> (2, 2)

Take a look at this post for further details.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386