Pyhton繼承

單繼承

class Father():
    def __init__(self):
        print("父類__init__")
        self.a = 1
        
class Son(Father):
    def __init__(self):
        print("子類__init__")
        self.b = 2

    def show_son(self):
        print(self.a, self.b)
        
if __name__ == "__main__":
    son = Son()
    son.show_son()

輸出:
子類__init__
AttributeError: ‘Son’ object has no attribute ‘a’

原因:
子類Son的__init__覆蓋了父類Father的__init__導致沒有屬性a

修改1:

class Father():
    def __init__(self):
        print("父類__init__")
        self.a = 1
        
class Son(Father):
    def __init__(self):
        # 方法一
#         Father.__init__(self) # 注意這裏的self爲Son的實例對象
        # 方法二
        super().__init__() # 不需要傳self
        print("子類__init__")
        self.b = 2

    def show_son(self):
        print(self.a, self.b)
        
if __name__ == "__main__":
    son = Son()
    son.show_son()

輸出:
父類__init__
子類__init__
1 2

多繼承

class Father():
    def __init__(self):
        print("父類Father__init__")
        self.father = 'father'
        
class Monther():
    def __init__(self):
        print("父類Monther__init__")
        self.monther = 'monther'
        
class Son(Father, Monther):
    def __init__(self):
        Father.__init__(self) # 注意這裏的self爲Son的實例對象
        Monther.__init__(self) # 注意這裏的self爲Son的實例對象
        print("子類__init__")
        self.son = 'son'

    def show_son(self):
        print(self.father, self.monther, self.son)
        
if __name__ == "__main__":
    son = Son()
    son.show_son()

輸出:
父類Father__init__
父類Monther__init__
子類__init__
father monther son

class Father():
    def __init__(self, father):
        print("父類Father__init__")
        self.father = father
        
class Monther():
    def __init__(self, monther):
        print("父類Monther__init__")
        self.monther = monther
        
class Son(Father, Monther):
    def __init__(self, father, monther, son):
        Father.__init__(self, father) # 注意這裏的self爲Son的實例對象
        Monther.__init__(self, monther) # 注意這裏的self爲Son的實例對象
        print("子類__init__")
        self.son = son

    def show_son(self):
        print(self.father, self.monther, self.son)
        
if __name__ == "__main__":
    son = Son("father", "monther", "son")
    son.show_son()

輸出:
父類Father__init__
父類Monther__init__
子類__init__
father monther son

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章