Python面向对象——基本继承

2018-06-18 02:19:36来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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 著

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python面向对象——内置对象的功能扩展

下一篇:Python爬虫学习==&gt;第十章:使用Requests+正则表达式爬取猫眼