简体   繁体   English

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

[英]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: 要在Python 2.7中调用父类的构造函数,我看到的标准代码是:

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

where Child is the child class. 其中Child是儿童班。 (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: (在Python 3.x中,这是简化的,但我现在必须使用2.7。)我的问题是,在python 2.7中使用super的“规范”不是更好:

super(self.__class__, self).__init__(self, val) ? 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. 在Python 3.x中,这是简化的,但我现在必须使用2.7。

A better way to call the super constructor in Python 2.7 is using Python-Future . 在Python 2.7中调用超级构造函数的更好方法是使用Python-Future It allows to use the Python 3 super() in Python 2 with: 它允许在Python 2中使用Python 3 super()

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. 当类被子类化时,此构造导致RecursionError

MCVE: MCVE:

class A(object):
    def __init__(self):
        super(self.__class__, self).__init__()


class B(A):
    pass

B()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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