在Python 2.7中,通过super(self .__ class__,self)调用Super Constructor不是更好吗?

PPr*_*eus 2 python inheritance super python-2.7 python-3.x

要在Python 2.7中调用父类的构造函数,我看到的标准代码是:

super(Child, self).__init__(self, val),

Child儿童班在哪里.(在Python 3.x中,这是简化的,但我现在必须使用2.7.)我的问题是,在python 2.7中使用super的"规范"不是更好:

super(self.__class__, self).__init__(self, val)

我测试了这个,它似乎工作.有没有理由不使用这种方法?

Mik*_*ler 5

在Python 3.x中,这是简化的,但我现在必须使用2.7.

在Python 2.7中调用超级构造函数的更好方法是使用Python-Future.它允许super()在Python 2中使用Python 3 :

from builtins import super  # from Python-Future

class Parent(object):
    def __init__(self):
        print('Hello')

class Child(Parent):
    def __init__(self):
        super().__init__()


Child()
Run Code Online (Sandbox Code Playgroud)

输出:

Hello
Run Code Online (Sandbox Code Playgroud)