本文通過圖解的方法解釋了Python面向對象中基本繼承的原理。 ...
1.基本繼承圖解
1.1實例化一個Contact類的對象c
1.2實例化一個Supplier類的對象s
1.3訪問對象的屬性
1.4訪問對象s的方法
1.5類變數詳解
如果從新定義c.all_contacts = "xxxxxx";那麼,對象c擁有一個新的屬性all_contacts,其值為"xxxxxx"。這個c對象屬性的修改,不影響Contact.all_contacts, Supplier.all_contacts, s.all_contacts的值。
註:上述通過對象訪問類變數,其實都是訪問同一個值,它們都屬於Contact.all_contacts;只要Contact.all_contacts不修改,實例化的對象就不會修改。
2上述代碼驗證
In [1]: class mySubclass(object): #繼承的基本語法 ...: pass ...: In [2]: class Contact: #父類定義 ...: all_contacts = [] ...: def __init__(self, name, email): ...: self.name = name ...: self.email = email ...: Contact.all_contacts.append(self) ...: In [3]: class Supplier(Contact): #子類定義,繼承了Contact類 ...: def order(self, order): ...: print("If this were a real system we would send " ...: "{} order to {} ".format(order, self.name)) ...: In [4]: c = Contact("Some Body", "[email protected]") In [5]: s = Supplier("Sup Plier", "[email protected]") In [6]: c.name Out[6]: 'Some Body' In [7]: c.email Out[7]: '[email protected]' In [8]: s.name Out[8]: 'Sup Plier' In [9]: s.email Out[9]: '[email protected]' In [10]: c.all_contacts Out[10]: [<__main__.Contact at 0x1e3f42bbb70>, <__main__.Supplier at 0x1e3f42c1278>] In [11]: c.order("I need plier") --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-11-728826faab97> in <module>() ----> 1 c.order("I need plier") AttributeError: 'Contact' object has no attribute 'order' In [12]: s.order("I need plier") If this were a real system we would send I need plier order to Sup Plier In [13]: s.all_contacts Out[13]: [<__main__.Contact at 0x1e3f42bbb70>, <__main__.Supplier at 0x1e3f42c1278>]
參考:本文參考學習《Python3 Object Oriented Programming》,Dusty Phillips 著