本文實(shí)例講述了Python實(shí)現(xiàn)帶參數(shù)與不帶參數(shù)的多重繼承。分享給大家供大家參考,具體如下:
1. 不帶參數(shù)的多重繼承
# 作者:hhh5460# 時(shí)間:2017.07.18class A(object): def show_x(self): print('A')class B(object): def show_y(self): print('B')class C(object): def show_z(self): print('C')class D(A, B, C): pass# 測(cè)試if __name__ == '__main__': d = D() d.show_x() # A d.show_y() # B d.show_z() # C2. 帶參數(shù)的多重繼承
# 作者:hhh5460# 時(shí)間:2017.07.18class A(object): def __init__(self, x=0): self._x = x def show_x(self): print(self._x) def show_name(self): print('A')class B(object): def __init__(self, y=0): self._y = y def show_y(self): print(self._y) def show_name(self): print('B')class C(object): def __init__(self, z=0): self._z = z def show_z(self): print(self._z) def show_name(self): print('C')# 注意下面兩類D、E,都是繼承A、B、C,且A類的優(yōu)先級(jí)最高。但是三條__init__語(yǔ)句的順序是相反的class D(A, B, C): def __init__(self, x=0, y=0, z=0): C.__init__(self, z) # init C B.__init__(self, y) # init B A.__init__(self, x) # init A (A最優(yōu)先)class E(A, B, C): def __init__(self, x=0, y=0, z=0): super(E, self).__init__(x) # init A (A最優(yōu)先) # 此句可簡(jiǎn)寫成:super().__init__(x) super(A, self).__init__(y) # init B super(B, self).__init__(z) # init C# 測(cè)試if __name__ == '__main__': d = D(1,2,3) d.show_x() # 1 d.show_y() # 2 d.show_z() # 3 d.show_name() # A e = E(1,2,3) e.show_x() # 1 e.show_y() # 2 e.show_z() # 3 e.show_name() # A更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選