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

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

问题描述

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

我很想知道以下 2 个子类之间的实际区别.

class Base(object):def __init__(self):打印基础创建"类 ChildA(基础):def __init__(self):Base.__init__(self)类 ChildB(基础):def __init__(self):super(ChildB, self).__init__()孩子A()子B()

解决方案

super() 可让您避免显式引用基类,这很好.但主要优势来自多重继承,其中各种有趣的东西可以发生.如果您还没有,请参阅super 标准文档.>

请注意语法在 Python 3.0 中发生了变化:您可以说 super().__init__() 而不是 super(ChildB, self).__init__() ,IMO 更好一些.标准文档还参考了 使用 super() 解释得很清楚.

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

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() 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.

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. The standard docs also refer to a guide to using super() which is quite explanatory.

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

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