使用__init __()方法理解Python super() [英] Understanding Python super() with __init__() methods

查看:103
本文介绍了使用__init __()方法理解Python super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解使用 super()。从它的外观来看,可以创建两个子类,就好了。

I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine.

我很想知道以下2个子课程之间的实际差异。

I'm curious to know about the actual difference between the following 2 child classes.

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()可以避免显式引用基类,这可能很好。但主要优势在于多重继承,其中各种各样的有趣的东西可以发生。如果您还没有,请参阅超级标准文档

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

请注意,语法已更改Python 3.0 :你可以说 super().__ init __()而不是 super(ChildB,self).__ init __()哪个IMO好一点。

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.

这篇关于使用__init __()方法理解Python super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆