为什么要使用super()
?
使用 Base.__init__
和 super().__init__
有区别吗?
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()
最佳答案
super()
让您避免显式引用基类,这很好。但主要优势在于多重继承,其中各种 fun stuff可以发生。见 standard docs on super如果你还没有。
请注意 the syntax changed in Python 3.0 :你可以说 super().__init__()
而不是 super(ChildB, self).__init__()
,IMO 更好一些。标准文档还引用了 guide to using super()
这很好解释。
关于python - 使用 __init__() 方法理解 Python super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/576169/