Python中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__() print ChildA(),ChildB()
super()的好处就是可以避免直接使用父类的名字.但是它主要用于多重继承。如果还不了解的话可以看看官方文档
注意:在Python3.0里语法有所改变:你可以用super().__init__()替换super(ChildB, self).__init__().(在我看来非常nice)
参考资料
- http://www.artima.com/weblogs/viewpost.jsp?thread=236275
- https://docs.python.org/2/library/functions.html#super
: » Python中super()和__init__()方法的区别
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/252515.html