为什么使用super()?
使用Base有区别吗__init__和super()__初始__?
class Base(object):
def __init__(self):
print "Base created"
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
已经注意到,在Python 3.0+中,您可以使用
super().__init__()
这是一种简洁的方法,不需要显式引用父类OR类名,这很方便。我只想补充一点,对于Python 2.7或更低版本,有些人通过编写self来实现不区分名称的行为__class__而不是类名,即。
super(self.__class__, self).__init__() # DON'T DO THIS!
然而,这中断了对从类继承的任何类的调用,其中self__class__可以返回子类。例如:
class Polygon(object):
def __init__(self, id):
self.id = id
class Rectangle(Polygon):
def __init__(self, id, width, height):
super(self.__class__, self).__init__(id)
self.shape = (width, height)
class Square(Rectangle):
pass
这里我有一个类Square,它是矩形的子类。假设我不想为Square编写单独的构造函数,因为Rectangle的构造函数已经足够好了,但无论出于什么原因,我都希望实现一个Square,这样我就可以重新实现一些其他方法。
当我使用mSquare=Square('a',10,10)创建Square时,Python调用Rectangle的构造函数,因为我没有给Square自己的构造函数。然而,在Rectangle的构造函数中,调用super(self.__class__,self)将返回mSquare的超类,因此它再次调用Rectangle构造函数。正如@S_C所提到的,无限循环就是这样发生的。在本例中,当我运行super(…).__init__()时,我正在调用Rectangle的构造函数,但由于我没有给它任何参数,所以会得到一个错误。