• 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 著

  • 相关阅读:
    移动端调试解决方案-转载
    移动端调试工具-Weinre
    css颜色大全-转载
    目录
    多版本python import 问题解决方案
    annoy安装
    word2vec
    GBDT
    Adaptive Boosting
    融合模型Aggregation
  • 原文地址:https://www.cnblogs.com/brightyuxl/p/8784562.html
Copyright © 2020-2023  润新知