Why is my inheritance / Python super example not working?
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 output is (1,1), while I expect to see (2,2).
Also, why am I getting deprecation warning for this object. init () takes no parameters? What should I do instead?
+3
source to share
1 answer
Tuples are immutable, you need 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)
This now works as expected:
a = CTest((1,1)) print a > (2, 2)
Take a look at this post for more information.
+5
source to share