Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

python - 通过__init __()方法了解Python super()(Understanding Python super() with __init__() methods [duplicate])

I'm trying to understand the use of super() .

(我试图了解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()
  ask by Mizipzor translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

super() lets you avoid referring to the base class explicitly, which can be nice.

(super()可以避免显式引用基类,这可能很好。)

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.

(如果还没有的话,请参阅关于super标准文档 。)

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.

(请注意, Python 3.0的语法已更改 :您只能说super().__init__()而不是super(ChildB, self).__init__() ,这对IMO来说要好得多。)

The standard docs also refer to a guide to using super() which is quite explanatory.

(标准文档还参考了使用super()指南,这是非常说明性的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...