Reputation: 599
To call the constructor of a parent class in Python 2.7, the standard code that I've seen is:
super(Child, self).__init__(self, val)
,
where Child
is the child class. (In Python 3.x, this is simplified, but I have to use 2.7 for now.) My question is, wouldn't it be better for the "canonical" use of super in python 2.7 to be:
super(self.__class__, self).__init__(self, val)
?
I've tested this, and it seems to work. Is there any reason not to use this approach?
Upvotes: 2
Views: 775
Reputation: 85442
In Python 3.x, this is simplified, but I have to use 2.7 for now.
A better way to call the super constructor in Python 2.7 is using Python-Future. It allows to use the Python 3 super()
in Python 2 with:
from builtins import super # from Python-Future
class Parent(object):
def __init__(self):
print('Hello')
class Child(Parent):
def __init__(self):
super().__init__()
Child()
Output:
Hello
Upvotes: 5
Reputation: 23213
This construct causes RecursionError
when class is subclassed.
MCVE:
class A(object):
def __init__(self):
super(self.__class__, self).__init__()
class B(A):
pass
B()
Upvotes: 4