简体   繁体   中英

In Python 2.7, isn't it better to call the Super Constructor via super(self.__class__, self)…?

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?

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM