内容字号:默认大号超大号

段落设置:段首缩进取消段首缩进

字体设置:切换到微软雅黑切换到宋体

Python面向对象:基本继承

2018-04-16 17:28 出处:清屏网 人气: 评论(0

1.基本继承图解

1.1实例化一个Contact类的对象c

1.2实例化一个Supplier类的对象s

1.3访问对象的属性

1.4访问对象的方法

1.5类变量详解

如果从新定义c.all_contacts = "xxxxxx";那么,对象c拥有一个新的属性all_contacts,其值为"xxxxxx"。这个c对象属性的修改,不影响Contact.all_contacts, Supplier.all_contacts, s.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>]
分享给小伙伴们:
本文标签: Python面向对象

相关文章

发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。

CopyRight © 2015-2016 QingPingShan.com , All Rights Reserved.

清屏网 版权所有 豫ICP备15026204号