[修]python普通繼承方式和super繼承方式


[轉]python普通繼承方式和super繼承方式

 

原文出自:http://www.360doc.com/content/13/0306/15/9934052_269664772.shtml

原文的錯誤,已經被我修改掉了。

 

 

 

普通繼承:

class FooParent(object):
    def __init__(self):
        self.parent='Im 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

結果:

>>> fooChild = FooChild()
Parent
Child
>>> fooChild.bar("Hello World")
Hello World from Parent
Child bar function.
Im the parent.

 

 
 
==========================================================
super繼承:
新建一個bo.py的文件
 
下面上代碼,方便未來人調試。
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__()  #意思跟上面差不多,只是這里直接調用的super尋找父輩函數,然后用了super的__init__()
        print 'Child'
# 這一點在多重繼承時體現得很明顯。在super機制里可以保證公共父類僅被執行一次,至於執行的順序,是按照mro進行的(E.__mro__)。
    def bar(self, message):
        super(FooChild, self).bar(message)
        print 'Child bar function. '
        print self.parent

開始檢驗結果:


    fooChild = FooChild()
    fooChild.bar("HelloWorld")

 從上面看起來,似乎結果是一樣的。

 
================================================================================
從運行結果上來看普通繼承跟super繼承是一樣的,但是其實它們的內部運行機制不太一樣,這一點在多重繼承時體現得很明顯。 在super機制里可以保證公共父類僅被執行一次,至於執行的順序,是按照mro進行的(E.__mro__)。 http://hi.baidu.com/thinkinginlamp/item/3095e2f52c642516ce9f32d5
 
注意super繼承只能用於新式類,用於經典類時就會報錯。
新式類:必須有繼承的類,如果沒什么想繼承的,那就繼承objcet
經典類:沒有父類,如果此時調用super就會出現錯誤:“ super() argument 1 must be type, not classobj
 
 這里我們把更多的內容加入到這個里面去:采用的是上面的那個鏈接  http://hi.baidu.com/thinkinginlamp/item/3095e2f52c642516ce9f32d5 這個一定要讀一下,代碼並不是很難,
給出的實例很科學的。贊賞一個。為了避免公共父類被執行多次,就采用了super(child, self).__init__() 

如何在Python中調用父類的同名方法

 
 
 
 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM