Python中super的用法執行個體

來源:互聯網
上載者:User

Python中super的用法執行個體

   這篇文章主要介紹了Python中super的用法執行個體,本文對比了普通繼承和super繼承的相關內容,從運行結果上看,普通繼承和super繼承是一樣的,但是其實它們的內部運行機制不一樣,這一點在多重繼承時體現得很明顯,需要的朋友可以參考下

  super 是用來解決多重繼承問題的,直接用類名調用父類方法在使用單繼承的時候沒問題,但是如果使用多繼承,會涉及到尋找順序(MRO)、重複調用(鑽石繼承)等種種問題。總之前人留下的經驗就是:保持一致性。要不全部用類名調用父類,要不就全部用 super,不要一半一半。

  普通繼承

  代碼如下:

  class FooParent(object):

  def __init__(self):

  self.parent = 'I\'m the parent.'

  print 'Parent'

  def bar(self,message):

  print message, 'from Parent'

  class FooChild(FooParent):

  def __init__(self):

  FooParent.__init__(self)

  print 'Child'

  def bar(self,message):

  FooParent.bar(self,message)

  print 'Child bar function.'

  print self.parent

  if __name__=='__main__':

  fooChild = FooChild()

  fooChild.bar('HelloWorld')

  super繼承

  代碼如下:

  class FooParent(object):

  def __init__(self):

  self.parent = 'I\'m the parent.'

  print 'Parent'

  def bar(self,message):

  print message,'from Parent'

  class FooChild(FooParent):

  def __init__(self):

  super(FooChild,self).__init__()

  print 'Child'

  def bar(self,message):

  super(FooChild, self).bar(message)

  print 'Child bar fuction'

  print self.parent

  if __name__ == '__main__':

  fooChild = FooChild()

  fooChild.bar('HelloWorld')

  程式運行結果相同,為:

  代碼如下:

  Parent

  Child

  HelloWorld from Parent

  Child bar fuction

  I'm the parent.

  從運行結果上看,普通繼承和super繼承是一樣的。但是其實它們的內部運行機制不一樣,這一點在多重繼承時體現得很明顯。在super機制裡可以保證公用父類僅被執行一次,至於執行的順序,是按照mro進行的(E.__mro__)。

  注意super繼承只能用於新式類,用於經典類時就會報錯。

  新式類:必須有繼承的類,如果沒什麼想繼承的,那就繼承object

  經典類:沒有父類,如果此時調用super就會出現錯誤:『super() argument 1 must be type, not classobj』

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.