为什么是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__()
,我认为这更好一些。标准文档还引用了 guide to using super()
这很容易解释。
关于python - 理解 Python super() 和 __init__() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220380/