zoukankan      html  css  js  c++  java
  • day07面向对象(初级篇)

    Python 面向对象(初级篇)

    本章内容简介:

    1. 模块(温习,主要是练习几个实例): 

      1)解析配置模块configparser;

      2)解析xml模块;

      3)文件压缩模块zipfile和tarfile;  

    2. 面向对象(初级篇)

    一. 模块

    2.1) 解析配置模块:configparser

    configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

    实例:

    • text文件,文件格式:
    [section1] # 节点
    k1 = v1    # 值
    k2:v2       # 值
     
    [section2] # 节点
    k1 = v1    # 值
    
    •  1.  以列表的形式获取所有节点名:
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    print(config)
    ret = config.sections()
    print(ret)
    

    执行结果:

    <configparser.ConfigParser object at 0x000000000114E860>
    ['section1', 'section2']

    代码解析:
    加载模块后,ConfigParser类( implementing interpolation)执行插入; read读取文件或是列表文件,可选字符集(得到的结果是一个内存地址);

    sections解释:Return a list of section names(全文检索返回节点名字的列表)

    • 2.  获取指定节点下所有的键值对
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    ret = config.items('section1')
    print(ret)
    

    执行结果:

    [('k1', 'v1'), ('k2', 'v2')]

    代码解析:

      items(‘节点名’),源码解释Return a list of (name, value) tuples for each option in a section。返回这个节点的key、value为元组的列表;

    • 3. 获取指定节点下指定key的值
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    v1 = config.get('section1', 'k1')
    v2 = config.get('section1', 'k2')
    print(v1,v2)
    

    执行结果:

    v1 v2
    

    代码解析:

      get(“节点名”,“key值”),获取节点下key值对应的value,如果输入的key值不存在,会报错;

    • 4. 获取指定节点下的键值
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    ret = config.options('section1')
    print(ret)
    

    执行结果:  ['k1', 'k2']

    代码解析:

      options(self, section) : Return a list of option names for the given section name.

    • 5. 检查、添加、删除节点
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    has_sec = config.has_section('section1')
    print(has_sec)
    

    执行结果:  True

    代码解析:

      has_section(self, section)检查: Indicate whether the named section is present in the configuration.  The DEFAULT section is not acknowledged.

      指明 两个中的一个:这个节点名在当前的配置里(返回True),这个默认的节点是不被承认的(返回False)。

    添加和删除

    # 添加一个节点
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    config.add_set('section3')
    config.write(open('text', 'w'))
    
    # 设置节点里的内容
    config.set('section3','k1','v1')
    config.write(open('text', 'w'))
    
    # 删除节点
    config.remove_section('section3')
    config.write(open('text', 'w'))
    
    • 6. 检查、删除、设置指定组内的键值对
    import configparser
    
    config = configparser.ConfigParser()
    config.read('text',encoding='utf-8')
    
    # 检查section1节点里是否存在k1这个名字;
    has_opt = config.has_option('section1', 'k1')
    print(has_opt)
    
    # 删除section1节点里是 k1的内容;
    config.remove_option('section1', 'k1')
    config.write(open('text', 'w'))
    
    # section1节点里设置一个值
    config.set('section1', 'k10', "123")
    config.write(open('text', 'w'))
    

    总结:

      当增、删、改文件的时候,要将改变写入文件; 

    2.2)解析xml模块:xml

     XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:

    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2023</year>
            <gdppc>141100</gdppc>
            <neighbor direction="E" name="Austria" />
            <neighbor direction="W" name="Switzerland" />
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2026</year>
            <gdppc>59900</gdppc>
            <neighbor direction="N" name="Malaysia" />
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2026</year>
            <gdppc>13600</gdppc>
            <neighbor direction="W" name="Costa Rica" />
            <neighbor direction="E" name="Colombia" />
        </country>
    </data>
    

    1、解析XML

    利用ElementTree.XML将字符串解析成xml对象

    from xml.etree import ElementTree as ET
    
    
    # 打开文件,读取XML内容
    str_xml = open('xo.xml', 'r').read()
    
    # 将字符串解析成xml特殊对象,root代指xml文件的根节点
    root = ET.XML(str_xml)
    

    获取的根节点data:  <Element 'data' at 0x00000000006E72C8>

    利用ElementTree.parse将文件直接解析成xml对象

    from xml.etree import ElementTree as ET
    
    # 直接解析xml文件
    tree = ET.parse("xo.xml")
    
    # 获取xml文件的根节点
    root = tree.getroot()
    

    获取的根节点data:  <Element 'data' at 0x00000000006E72C8>

    2、操作XML

    XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:

    节点功能一览表

    class Element:
        """An XML element.
    
        This class is the reference implementation of the Element interface.
    
        An element's length is its number of subelements.  That means if you
        want to check if an element is truly empty, you should check BOTH
        its length AND its text attribute.
    
        The element tag, attribute names, and attribute values can be either
        bytes or strings.
    
        *tag* is the element name.  *attrib* is an optional dictionary containing
        element attributes. *extra* are additional element attributes given as
        keyword arguments.
    
        Example form:
            <tag attrib>text<child/>...</tag>tail
    
        """
    
        当前节点的标签名
        tag = None
        """The element's name."""
    
        当前节点的属性
    
        attrib = None
        """Dictionary of the element's attributes."""
    
        当前节点的内容
        text = None
        """
        Text before first subelement. This is either a string or the value None.
        Note that if there is no text, this attribute may be either
        None or the empty string, depending on the parser.
    
        """
    
        tail = None
        """
        Text after this element's end tag, but before the next sibling element's
        start tag.  This is either a string or the value None.  Note that if there
        was no text, this attribute may be either None or an empty string,
        depending on the parser.
    
        """
    
        def __init__(self, tag, attrib={}, **extra):
            if not isinstance(attrib, dict):
                raise TypeError("attrib must be dict, not %s" % (
                    attrib.__class__.__name__,))
            attrib = attrib.copy()
            attrib.update(extra)
            self.tag = tag
            self.attrib = attrib
            self._children = []
    
        def __repr__(self):
            return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
    
        def makeelement(self, tag, attrib):
            创建一个新节点
            """Create a new element with the same type.
    
            *tag* is a string containing the element name.
            *attrib* is a dictionary containing the element attributes.
    
            Do not call this method, use the SubElement factory function instead.
    
            """
            return self.__class__(tag, attrib)
    
        def copy(self):
            """Return copy of current element.
    
            This creates a shallow copy. Subelements will be shared with the
            original tree.
    
            """
            elem = self.makeelement(self.tag, self.attrib)
            elem.text = self.text
            elem.tail = self.tail
            elem[:] = self
            return elem
    
        def __len__(self):
            return len(self._children)
    
        def __bool__(self):
            warnings.warn(
                "The behavior of this method will change in future versions.  "
                "Use specific 'len(elem)' or 'elem is not None' test instead.",
                FutureWarning, stacklevel=2
                )
            return len(self._children) != 0 # emulate old behaviour, for now
    
        def __getitem__(self, index):
            return self._children[index]
    
        def __setitem__(self, index, element):
            # if isinstance(index, slice):
            #     for elt in element:
            #         assert iselement(elt)
            # else:
            #     assert iselement(element)
            self._children[index] = element
    
        def __delitem__(self, index):
            del self._children[index]
    
        def append(self, subelement):
            为当前节点追加一个子节点
            """Add *subelement* to the end of this element.
    
            The new element will appear in document order after the last existing
            subelement (or directly after the text, if it's the first subelement),
            but before the end tag for this element.
    
            """
            self._assert_is_element(subelement)
            self._children.append(subelement)
    
        def extend(self, elements):
            为当前节点扩展 n 个子节点
            """Append subelements from a sequence.
    
            *elements* is a sequence with zero or more elements.
    
            """
            for element in elements:
                self._assert_is_element(element)
            self._children.extend(elements)
    
        def insert(self, index, subelement):
            在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
            """Insert *subelement* at position *index*."""
            self._assert_is_element(subelement)
            self._children.insert(index, subelement)
    
        def _assert_is_element(self, e):
            # Need to refer to the actual Python implementation, not the
            # shadowing C implementation.
            if not isinstance(e, _Element_Py):
                raise TypeError('expected an Element, not %s' % type(e).__name__)
    
        def remove(self, subelement):
            在当前节点在子节点中删除某个节点
            """Remove matching subelement.
    
            Unlike the find methods, this method compares elements based on
            identity, NOT ON tag value or contents.  To remove subelements by
            other means, the easiest way is to use a list comprehension to
            select what elements to keep, and then use slice assignment to update
            the parent element.
    
            ValueError is raised if a matching element could not be found.
    
            """
            # assert iselement(element)
            self._children.remove(subelement)
    
        def getchildren(self):
            获取所有的子节点(废弃)
            """(Deprecated) Return all subelements.
    
            Elements are returned in document order.
    
            """
            warnings.warn(
                "This method will be removed in future versions.  "
                "Use 'list(elem)' or iteration over elem instead.",
                DeprecationWarning, stacklevel=2
                )
            return self._children
    
        def find(self, path, namespaces=None):
            获取第一个寻找到的子节点
            """Find first matching element by tag name or path.
    
            *path* is a string having either an element tag or an XPath,
            *namespaces* is an optional mapping from namespace prefix to full name.
    
            Return the first matching element, or None if no element was found.
    
            """
            return ElementPath.find(self, path, namespaces)
    
        def findtext(self, path, default=None, namespaces=None):
            获取第一个寻找到的子节点的内容
            """Find text for first matching element by tag name or path.
    
            *path* is a string having either an element tag or an XPath,
            *default* is the value to return if the element was not found,
            *namespaces* is an optional mapping from namespace prefix to full name.
    
            Return text content of first matching element, or default value if
            none was found.  Note that if an element is found having no text
            content, the empty string is returned.
    
            """
            return ElementPath.findtext(self, path, default, namespaces)
    
        def findall(self, path, namespaces=None):
            获取所有的子节点
            """Find all matching subelements by tag name or path.
    
            *path* is a string having either an element tag or an XPath,
            *namespaces* is an optional mapping from namespace prefix to full name.
    
            Returns list containing all matching elements in document order.
    
            """
            return ElementPath.findall(self, path, namespaces)
    
        def iterfind(self, path, namespaces=None):
            获取所有指定的节点,并创建一个迭代器(可以被for循环)
            """Find all matching subelements by tag name or path.
    
            *path* is a string having either an element tag or an XPath,
            *namespaces* is an optional mapping from namespace prefix to full name.
    
            Return an iterable yielding all matching elements in document order.
    
            """
            return ElementPath.iterfind(self, path, namespaces)
    
        def clear(self):
            清空节点
            """Reset element.
    
            This function removes all subelements, clears all attributes, and sets
            the text and tail attributes to None.
    
            """
            self.attrib.clear()
            self._children = []
            self.text = self.tail = None
    
        def get(self, key, default=None):
            获取当前节点的属性值
            """Get element attribute.
    
            Equivalent to attrib.get, but some implementations may handle this a
            bit more efficiently.  *key* is what attribute to look for, and
            *default* is what to return if the attribute was not found.
    
            Returns a string containing the attribute value, or the default if
            attribute was not found.
    
            """
            return self.attrib.get(key, default)
    
        def set(self, key, value):
            为当前节点设置属性值
            """Set element attribute.
    
            Equivalent to attrib[key] = value, but some implementations may handle
            this a bit more efficiently.  *key* is what attribute to set, and
            *value* is the attribute value to set it to.
    
            """
            self.attrib[key] = value
    
        def keys(self):
            获取当前节点的所有属性的 key
    
            """Get list of attribute names.
    
            Names are returned in an arbitrary order, just like an ordinary
            Python dict.  Equivalent to attrib.keys()
    
            """
            return self.attrib.keys()
    
        def items(self):
            获取当前节点的所有属性值,每个属性都是一个键值对
            """Get element attributes as a sequence.
    
            The attributes are returned in arbitrary order.  Equivalent to
            attrib.items().
    
            Return a list of (name, value) tuples.
    
            """
            return self.attrib.items()
    
        def iter(self, tag=None):
            在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
            """Create tree iterator.
    
            The iterator loops over the element and all subelements in document
            order, returning all elements with a matching tag.
    
            If the tree structure is modified during iteration, new or removed
            elements may or may not be included.  To get a stable set, use the
            list() function on the iterator, and loop over the resulting list.
    
            *tag* is what tags to look for (default is to return all elements)
    
            Return an iterator containing all the matching elements.
    
            """
            if tag == "*":
                tag = None
            if tag is None or self.tag == tag:
                yield self
            for e in self._children:
                yield from e.iter(tag)
    
        # compatibility
        def getiterator(self, tag=None):
            # Change for a DeprecationWarning in 1.4
            warnings.warn(
                "This method will be removed in future versions.  "
                "Use 'elem.iter()' or 'list(elem.iter())' instead.",
                PendingDeprecationWarning, stacklevel=2
            )
            return list(self.iter(tag))
    
        def itertext(self):
            在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
            """Create text iterator.
    
            The iterator loops over the element and all subelements in document
            order, returning all inner text.
    
            """
            tag = self.tag
            if not isinstance(tag, str) and tag is not None:
                return
            if self.text:
                yield self.text
            for e in self:
                yield from e.itertext()
                if e.tail:
                    yield e.tail
    

    由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so   可以利用以上方法进行操作xml文件。

    a. 遍历XML文档的所有内容

    from xml.etree import ElementTree as ET
    
    # 直接解析xml文件
    tree = ET.parse("xo.xml")
    
    # 获取xml文件的根节点
    root = tree.getroot()
    
    ### 操作
    
    # 顶层标签
    print(root.tag)
    
    # 遍历XML文档的第二层
    for child in root:
        # 第二层节点的标签名称和标签属性
        print(child.tag, child.attrib)
        # 遍历XML文档的第三层
        for i in child:
            # 第二层节点的标签名称和内容
            print(i.tag,i.text)
    

    执行结果:

    data
    country {'name': 'Liechtenstein'}
    rank 2
    year 2023
    gdppc 141100
    neighbor None
    neighbor None
    country {'name': 'Singapore'}
    rank 5
    year 2026
    gdppc 59900
    neighbor None
    country {'name': 'Panama'}
    rank 69
    year 2026
    gdppc 13600
    neighbor None
    neighbor None
    

    b、遍历XML中指定的节点

    from xml.etree import ElementTree as ET
    
    # 直接解析xml文件
    tree = ET.parse("xo.xml")
    # 获取xml文件的根节点
    root = tree.getroot()
    
    ### 操作
    # 顶层标签
    print(root.tag)
    # 遍历XML中所有的year节点
    for node in root.iter('year'):
        # 节点的标签名称和内容
        print(node.tag, node.text)
    

    执行结果:

    data
    year 2023
    year 2026
    year 2026
    

    c、修改节点内容

    由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。

    • 方法一,解析字符串方式,修改,保存:
    from xml.etree import ElementTree as ET
    
    # 打开文件,读取XML内容
    str_xml = open('xo.xml', 'r').read()
    # 将字符串解析成xml特殊对象,root代指xml文件的根节点
    root = ET.XML(str_xml)
    ############ 操作 ############
    # 顶层标签
    print(root.tag)
    # 循环所有的year节点
    for node in root.iter('year'):
        # 将year节点中的内容自增一
        new_year = int(node.text) + 1
        node.text = str(new_year)
        # 设置属性
        node.set('name', 'alex')
        node.set('age', '18')
        # 删除属性
        del node.attrib['name']
    ############ 保存文件 ############
    tree = ET.ElementTree(root)
    tree.write("newnew.xml", encoding='utf-8')
    

    执行结果:

      打印输出一个data(根节点),将改过的文件另存为 newnew.xml。

    • 方法二,解析文件方式,修改,保存:
    from xml.etree import ElementTree as ET
    
    ############ 解析方式二 ############
    
    # 直接解析xml文件
    tree = ET.parse("xo.xml")
    # 获取xml文件的根节点
    root = tree.getroot()
    ############ 操作 ############
    # 顶层标签
    print(root.tag)
    
    # 循环所有的year节点
    for node in root.iter('year'):
        # 将year节点中的内容自增一
        new_year = int(node.text) + 1
        node.text = str(new_year)
    
        # 设置属性
        node.set('name', 'alex')
        node.set('age', '18')
        # 删除属性
        del node.attrib['name']
    
    ############ 保存文件 ############
    tree.write("newnew.xml", encoding='utf-8')
    

    d、删除节点

    方法一,解析字符串方式打开,删除,保存:

    from xml.etree import ElementTree as ET
    
    ############ 解析字符串方式打开 ############
    
    # 打开文件,读取XML内容
    str_xml = open('xo.xml', 'r').read()
    
    # 将字符串解析成xml特殊对象,root代指xml文件的根节点
    root = ET.XML(str_xml)
    
    ############ 操作 ############
    
    # 顶层标签
    print(root.tag)
    
    # 遍历data下的所有country节点
    for country in root.findall('country'):
        # 获取每一个country节点下rank节点的内容
        rank = int(country.find('rank').text)
    
        if rank > 50:
            # 删除指定country节点
            root.remove(country)
    
    ############ 保存文件 ############
    tree = ET.ElementTree(root)
    tree.write("newnew.xml", encoding='utf-8')
    

    方法二,解析文件方式打开,删除,保存:

    from xml.etree import ElementTree as ET
    
    ############ 解析文件方式 ############
    
    # 直接解析xml文件
    tree = ET.parse("xo.xml")
    
    # 获取xml文件的根节点
    root = tree.getroot()
    
    ############ 操作 ############
    
    # 顶层标签
    print(root.tag)
    
    # 遍历data下的所有country节点
    for country in root.findall('country'):
        # 获取每一个country节点下rank节点的内容
        rank = int(country.find('rank').text)
    
        if rank > 50:
            # 删除指定country节点
            root.remove(country)
    
    ############ 保存文件 ############
    tree.write("newnew.xml", encoding='utf-8')

    3、创建XML文档

    方法一:

    from xml.etree import ElementTree as ET
    
    
    # 创建根节点
    root = ET.Element("famliy")
    
    
    # 创建节点大儿子
    son1 = ET.Element('son', {'name': '儿1'})
    # 创建小儿子
    son2 = ET.Element('son', {"name": '儿2'})
    
    # 在大儿子中创建两个孙子
    grandson1 = ET.Element('grandson', {'name': '儿11'})
    grandson2 = ET.Element('grandson', {'name': '儿12'})
    son1.append(grandson1)
    son1.append(grandson2)
    
    
    # 把儿子添加到根节点中
    root.append(son1)
    root.append(son1)
    
    tree = ET.ElementTree(root)
    tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
    

    方法二:

    from xml.etree import ElementTree as ET
    
    # 创建根节点
    root = ET.Element("famliy")
    
    
    # 创建大儿子
    # son1 = ET.Element('son', {'name': '儿1'})
    son1 = root.makeelement('son', {'name': '儿1'})
    # 创建小儿子
    # son2 = ET.Element('son', {"name": '儿2'})
    son2 = root.makeelement('son', {"name": '儿2'})
    
    # 在大儿子中创建两个孙子
    # grandson1 = ET.Element('grandson', {'name': '儿11'})
    grandson1 = son1.makeelement('grandson', {'name': '儿11'})
    # grandson2 = ET.Element('grandson', {'name': '儿12'})
    grandson2 = son1.makeelement('grandson', {'name': '儿12'})
    
    son1.append(grandson1)
    son1.append(grandson2)
    
    
    # 把儿子添加到根节点中
    root.append(son1)
    root.append(son1)
    
    tree = ET.ElementTree(root)
    tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
    

    方法三:

    from xml.etree import ElementTree as ET
    
    
    # 创建根节点
    root = ET.Element("famliy")
    
    
    # 创建节点大儿子
    son1 = ET.SubElement(root, "son", attrib={'name': '儿1'})
    # 创建小儿子
    son2 = ET.SubElement(root, "son", attrib={"name": "儿2"})
    
    # 在大儿子中创建一个孙子
    grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'})
    grandson1.text = '孙子'
    
    
    et = ET.ElementTree(root)  #生成文档对象
    et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)

    由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:

    from xml.etree import ElementTree as ET
    from xml.dom import minidom
    
    
    def prettify(elem):
        """将节点转换成字符串,并添加缩进。
        """
        rough_string = ET.tostring(elem, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="	")
    
    # 创建根节点
    root = ET.Element("famliy")
    
    
    # 创建大儿子
    # son1 = ET.Element('son', {'name': '儿1'})
    son1 = root.makeelement('son', {'name': '儿1'})
    # 创建小儿子
    # son2 = ET.Element('son', {"name": '儿2'})
    son2 = root.makeelement('son', {"name": '儿2'})
    
    # 在大儿子中创建两个孙子
    # grandson1 = ET.Element('grandson', {'name': '儿11'})
    grandson1 = son1.makeelement('grandson', {'name': '儿11'})
    # grandson2 = ET.Element('grandson', {'name': '儿12'})
    grandson2 = son1.makeelement('grandson', {'name': '儿12'})
    
    son1.append(grandson1)
    son1.append(grandson2)
    
    
    # 把儿子添加到根节点中
    root.append(son1)
    root.append(son1)
    
    
    raw_str = prettify(root)
    
    f = open("xxxoo.xml",'w',encoding='utf-8')
    f.write(raw_str)
    f.close()

    2.3)文件压缩模块:(tarfile 和 zipfile)

     tarfile模块使用:

    import tarfile
    
    tar = tarfile.open('your.tar','w')
    tar.add('test1.py',arcname='a.py')
    tar.add('text',arcname='text123')
    tar.close()
    

    代码解析:

      tarfile压缩,首先要用open创建一个压缩文件,w只写;然后使用add将文件添加到压缩文件里,还可以使用arcname重新命名;最后close关闭文件;

    解压tarfile:

    tar = tarfile.open('your.tar','r')
    tar.extractall()  # 全部解压
    
    obj = tar.getmember('a.py')
    tar.extract(obj)  #解压指定文件
    tar.close()

    代码解析:

      tarfile解压缩,首先要用open打开一个压缩文件,r只读;然后使用extractall全部解压,或是使用getmember获取元素,使用extract解压获取的指定文件;最后close关闭文件;

    zipfile模块使用:

    import zipfile
    
    # 压缩
    z = zipfile.ZipFile('laxi.zip', 'w')
    z.write('a.log') #每次写入一个文件,多个只会写入最后一个;
    z.write('data.data')
    z.close()
    
    z = zipfile.ZipFile('laxi.zip', 'a')
    z.write('data.data')# 如果文件已存在,仍然继续写入副本,打印警告信息;
    z.close()

    解压缩:

    import zipfile
    
    # 解压缩
    z = zipfile.ZipFile('laxi.zip', 'r')
    z.extractall()# 解压全部;
    z.close()
    
    # 查看成员
    li = z.namelist()
    z.close()
    print(li) #成员将以列表的形式显示
    
    #解压指定成员;
    obj = z.getinfo('text') #获取指定成员
    z.extract(obj) # 解压
    z.close()

    二. 面向对象(初级篇)

    简述Python编程的三种形式:

    • 面向过程:根据业务逻辑从上到下写垒代码
    • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
    • 面向对象:对函数进行分类和封装,让开发“更快更好更强...“

    面向对象编程(Object Oriented Programming,OOP,面向对象程序设计);

    简单来说,面向对象编程就是使用class创建一个类,类里创建一些方法(每个方法是一个函数),创建类的对象,对象来调用类里的方法,执行;

    面向对象三大特性

    面向对象的三大特性是指:封装、继承和多态。

    一、封装

    封装,顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容。

    所以,在使用面向对象的封装特性时,需要:

    • 将内容封装到某处
    • 从某处调用被封装的内容

    第一步:将内容封装到某处

    对象的参数被封装到对象里,对象本身带人到init函数的self中使用,self == obj1,self是一个形式参数等于对象本身;

    所以,内容其实被封装到了对象 obj1 和 obj2 中,每个对象中都有 name 和 age 属性。

    第二步:从某处调用被封装的内容

    调用被封装的内容时,有两种情况:

    • 通过对象直接调用
    • 通过self间接调用

    对于面向对象的封装来说,其实就是使用构造方法将内容封装到 对象 中,然后通过对象直接或者self间接获取被封装的内容。

    二、继承

    继承,面向对象中的继承和现实生活中的继承相同,即:子可以继承父的内容。

    例如:

    动物:吃、喝、拉、撒

         猫:喵喵叫(猫继承动物的功能)

         狗:汪汪叫(狗继承动物的功能)

    class 动物:
    
        def 吃(self):
            # do something
    
        def 喝(self):
            # do something
    
        def 拉(self):
            # do something
    
        def 撒(self):
            # do something
    
    # 在类后面括号中写入另外一个类名,表示当前类继承另外一个类
    class 猫(动物):
    
        def 喵喵叫(self):
            print '喵喵叫'
            
    # 在类后面括号中写入另外一个类名,表示当前类继承另外一个类
    class 狗(动物):
    
        def 汪汪叫(self):
            print '汪汪叫'

    所以,对于面向对象的继承来说,其实就是将多个类共有的方法提取到父类中,子类仅需继承父类而不必一一实现每个方法。

    注:除了子类和父类的称谓,你可能看到过 派生类 和 基类 ,他们与子类和父类只是叫法不同而已。

    Python可以多继承,什么是多继承?

    1、Python的类可以继承多个类,Java和C#中则只能继承一个类

    2、Python的类如果继承了多个类,那么其寻找方法的方式有两种,分别是:深度优先广度优先

    • 当类是经典类时,多继承情况下,会按照深度优先方式查找
    • 当类是新式类时,多继承情况下,会按照广度优先方式查找

    经典类和新式类,从字面上可以看出一个老一个新,新的必然包含了跟多的功能,也是之后推荐的写法,从写法上区分的话,如果 当前类或者父类继承了object类,那么该类便是新式类,否则便是经典类。

    • 经典类多继承
    class D:
    
        def bar(self):
            print 'D.bar'
    
    
    class C(D):
    
        def bar(self):
            print 'C.bar'
    
    
    class B(D):
    
        def bar(self):
            print 'B.bar'
    
    
    class A(B, C):
    
        def bar(self):
            print 'A.bar'
    
    a = A()
    # 执行bar方法时
    # 首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去D类中找,如果D类中么有,则继续去C类中找,如果还是未找到,则报错
    # 所以,查找顺序:A --> B --> D --> C
    # 在上述查找bar方法的过程中,一旦找到,则寻找过程立即中断,便不会再继续找了
    a.bar()
    
    • 新式类多继承
    class D(object):
    
        def bar(self):
            print 'D.bar'
    
    
    class C(D):
    
        def bar(self):
            print 'C.bar'
    
    
    class B(D):
    
        def bar(self):
            print 'B.bar'
    
    
    class A(B, C):
    
        def bar(self):
            print 'A.bar'
    
    a = A()
    # 执行bar方法时
    # 首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去C类中找,如果C类中么有,则继续去D类中找,如果还是未找到,则报错
    # 所以,查找顺序:A --> B --> C --> D
    # 在上述查找bar方法的过程中,一旦找到,则寻找过程立即中断,便不会再继续找了
    a.bar()
    
    

    经典类:首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去D类中找,如果D类中么有,则继续去C类中找,如果还是未找到,则报错

    新式类:首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去C类中找,如果C类中么有,则继续去D类中找,如果还是未找到,则报错

    注意:在上述查找过程中,一旦找到,则寻找过程立即中断,便不会再继续找了

    三、多态 

     Pyhon不支持多态并且也用不到多态,多态的概念是应用于Java和C#这一类强类型语言中,而Python崇尚“鸭子类型”。

    • Python伪代码实现Java或C#的多态
    class F1:
        pass
    
    
    class S1(F1):
    
        def show(self):
            print 'S1.show'
    
    
    class S2(F1):
    
        def show(self):
            print 'S2.show'
    
    
    # 由于在Java或C#中定义函数参数时,必须指定参数的类型
    # 为了让Func函数既可以执行S1对象的show方法,又可以执行S2对象的show方法,所以,定义了一个S1和S2类的父类
    # 而实际传入的参数是:S1对象和S2对象
    
    def Func(F1 obj):
        """Func函数需要接收一个F1类型或者F1子类的类型"""
        
        print obj.show()
        
    s1_obj = S1()
    Func(s1_obj) # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法,结果:S1.show
    
    s2_obj = S2()
    Func(s2_obj) # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法,结果:S2.show
    
    • Python “鸭子类型”
    class F1:
        pass
    
    
    class S1(F1):
    
        def show(self):
            print 'S1.show'
    
    
    class S2(F1):
    
        def show(self):
            print 'S2.show'
    
    def Func(obj):
        print obj.show()
    
    s1_obj = S1()
    Func(s1_obj) 
    
    s2_obj = S2()
    Func(s2_obj) 
    

    总结 

    以上就是本节对于面向对象初级知识的介绍,总结如下:

    • 面向对象是一种编程方式,此编程方式的实现是基于对  和 对象 的使用
    • 类 是一个模板,模板中包装了多个“函数”供使用
    • 对象,根据模板创建的实例(即:对象),实例用于调用被包装在类中的函数
    • 面向对象三大特性:封装、继承和多态

     

  • 相关阅读:
    Design and Implementation of the Sun Network File System
    Flash: An Efficient and Portable Web Server
    Java集合框架练习-计算表达式的值
    后缀数组专题训练
    经典问题-生产者和消费者问题
    ubuntu14.04下配置Java环境以及安装最新版本的eclipse
    Java多线程之CountDownLatch学习
    ZooKeerper学习之Watcher
    ZooKeeper之FastLeaderElection算法详解
    python获取当天日期进行格式转换
  • 原文地址:https://www.cnblogs.com/liuhailong-py-way/p/5599213.html
Copyright © 2011-2022 走看看