Python面向对象——基本继承
程序员文章站
2024-01-11 15:28:46
本文通过图解的方法解释了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", "somebody@example.net") In [5]: s = Supplier("Sup Plier", "supplier@example.net") In [6]: c.name Out[6]: 'Some Body' In [7]: c.email Out[7]: 'somebody@example.net' In [8]: s.name Out[8]: 'Sup Plier' In [9]: s.email Out[9]: 'supplier@example.net' 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 著
上一篇: <<oracle database 11gR2 性能调整与优化 >&g
下一篇: 数组合并