Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Python inheritance/super example not work?

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?

like image 385
user1308523 Avatar asked Mar 01 '26 13:03

user1308523


1 Answers

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.

like image 56
Óscar López Avatar answered Mar 03 '26 01:03

Óscar López