Python之路_Day7

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之路_Day7相关的知识,希望对你有一定的参考价值。

Python之路_Day7_课堂笔记

前期回顾
一、作业
1、ATM
2、计算器


本期内容
一、模块
1、configparser
2、XML
3、shutil
4、subprocess系统命令

二、面向对象(上)
1、面向对象基础
2、面向对象编程和函数式编程对比
3、面向对象中对象和类的关系
4、面向对象之构造方法
5、面向对象之应用场景实例
6、面向对象之对象中封装对象
7、面向对象之单继承
8、面向对象之多继承


一、模块
1、configparser
用于处理特定格式的文件,其本质上是利用open来操作文件
  1. conf文件
  2. [section1]
  3. k1 = 123
  4. k2 = v2
  5. [section2]
  6. k1 = v1
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import configparser
  5. config = configparser.ConfigParser()
  6. config.read("conf",encoding=‘utf-8‘)
  7. # 获取所有节点
  8. ret = config.sections()
  9. print(ret)
  10. # 获取指定节点下所有的键值对
  11. ret = config.items(‘section1‘)
  12. print(ret)
  13. # 获取指定节点下所有的建
  14. ret = config.options(‘section1‘)
  15. print(ret)
  16. # 获取指定节点下指定key的值
  17. v = config.get(‘section1‘, ‘k1‘)
  18. # v = config.getint(‘section1‘, ‘k1‘)
  19. # v = config.getfloat(‘section1‘, ‘k1‘)
  20. # v = config.getboolean(‘section1‘, ‘k1‘)
  21. print(v)
  22. # 检查、删除、添加节点
  23. # 检查
  24. has_sec = config.has_section(‘section1‘)
  25. print(has_sec)
  26. # 添加节点
  27. config.add_section("SEC_1")
  28. config.write(open(‘xxxooo‘, ‘w‘))
  29. # 删除节点
  30. config.remove_section("SEC_1")
  31. config.write(open(‘xxxooo‘, ‘w‘))
  32. # 检查、删除、设置指定组内的键值对
  33. # 检查
  34. has_opt = config.has_option(‘section1‘, ‘k1‘)
  35. print(has_opt)
  36. # 删除
  37. config.remove_option(‘section1‘, ‘k1‘)
  38. config.write(open(‘xxxooo‘, ‘w‘))
  39. # 设置
  40. config.set(‘section1‘, ‘k10‘, "123")
  41. config.write(open(‘conf‘, ‘w‘))

2、XML
XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:
  1. class Element:
  2. """An XML element.
  3. This class is the reference implementation of the Element interface.
  4. An element‘s length is its number of subelements. That means if you
  5. want to check if an element is truly empty, you should check BOTH
  6. its length AND its text attribute.
  7. The element tag, attribute names, and attribute values can be either
  8. bytes or strings.
  9. *tag* is the element name. *attrib* is an optional dictionary containing
  10. element attributes. *extra* are additional element attributes given as
  11. keyword arguments.
  12. Example form:
  13. <tag attrib>text<child/>...</tag>tail
  14. """
  15. 当前节点的标签名
  16. tag = None
  17. """The element‘s name."""
  18. 当前节点的属性
  19. attrib = None
  20. """Dictionary of the element‘s attributes."""
  21. 当前节点的内容
  22. text = None
  23. """
  24. Text before first subelement. This is either a string or the value None.
  25. Note that if there is no text, this attribute may be either
  26. None or the empty string, depending on the parser.
  27. """
  28. tail = None
  29. """
  30. Text after this element‘s end tag, but before the next sibling element‘s
  31. start tag. This is either a string or the value None. Note that if there
  32. was no text, this attribute may be either None or an empty string,
  33. depending on the parser.
  34. """
  35. def __init__(self, tag, attrib={}, **extra):
  36. if not isinstance(attrib, dict):
  37. raise TypeError("attrib must be dict, not %s" % (
  38. attrib.__class__.__name__,))
  39. attrib = attrib.copy()
  40. attrib.update(extra)
  41. self.tag = tag
  42. self.attrib = attrib
  43. self._children = []
  44. def __repr__(self):
  45. return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
  46. def makeelement(self, tag, attrib):
  47. 创建一个新节点
  48. """Create a new element with the same type.
  49. *tag* is a string containing the element name.
  50. *attrib* is a dictionary containing the element attributes.
  51. Do not call this method, use the SubElement factory function instead.
  52. """
  53. return self.__class__(tag, attrib)
  54. def copy(self):
  55. """Return copy of current element.
  56. This creates a shallow copy. Subelements will be shared with the
  57. original tree.
  58. """
  59. elem = self.makeelement(self.tag, self.attrib)
  60. elem.text = self.text
  61. elem.tail = self.tail
  62. elem[:] = self
  63. return elem
  64. def __len__(self):
  65. return len(self._children)
  66. def __bool__(self):
  67. warnings.warn(
  68. "The behavior of this method will change in future versions. "
  69. "Use specific ‘len(elem)‘ or ‘elem is not None‘ test instead.",
  70. FutureWarning, stacklevel=2
  71. )
  72. return len(self._children) != 0 # emulate old behaviour, for now
  73. def __getitem__(self, index):
  74. return self._children[index]
  75. def __setitem__(self, index, element):
  76. # if isinstance(index, slice):
  77. # for elt in element:
  78. # assert iselement(elt)
  79. # else:
  80. # assert iselement(element)
  81. self._children[index] = element
  82. def __delitem__(self, index):
  83. del self._children[index]
  84. def append(self, subelement):
  85. 为当前节点追加一个子节点
  86. """Add *subelement* to the end of this element.
  87. The new element will appear in document order after the last existing
  88. subelement (or directly after the text, if it‘s the first subelement),
  89. but before the end tag for this element.
  90. """
  91. self._assert_is_element(subelement)
  92. self._children.append(subelement)
  93. def extend(self, elements):
  94. 为当前节点扩展 n 个子节点
  95. """Append subelements from a sequence.
  96. *elements* is a sequence with zero or more elements.
  97. """
  98. for element in elements:
  99. self._assert_is_element(element)
  100. self._children.extend(elements)
  101. def insert(self, index, subelement):
  102. 在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
  103. """Insert *subelement* at position *index*."""
  104. self._assert_is_element(subelement)
  105. self._children.insert(index, subelement)
  106. def _assert_is_element(self, e):
  107. # Need to refer to the actual Python implementation, not the
  108. # shadowing C implementation.
  109. if not isinstance(e, _Element_Py):
  110. raise TypeError(‘expected an Element, not %s‘ % type(e).__name__)
  111. def remove(self, subelement):
  112. 在当前节点在子节点中删除某个节点
  113. """Remove matching subelement.
  114. Unlike the find methods, this method compares elements based on
  115. identity, NOT ON tag value or contents. To remove subelements by
  116. other means, the easiest way is to use a list comprehension to
  117. select what elements to keep, and then use slice assignment to update
  118. the parent element.
  119. ValueError is raised if a matching element could not be found.
  120. """
  121. # assert iselement(element)
  122. self._children.remove(subelement)
  123. def getchildren(self):
  124. 获取所有的子节点(废弃)
  125. """(Deprecated) Return all subelements.
  126. Elements are returned in document order.
  127. """
  128. warnings.warn(
  129. "This method will be removed in future versions. "
  130. "Use ‘list(elem)‘ or iteration over elem instead.",
  131. DeprecationWarning, stacklevel=2
  132. )
  133. return self._children
  134. def find(self, path, namespaces=None):
  135. 获取第一个寻找到的子节点
  136. """Find first matching element by tag name or path.
  137. *path* is a string having either an element tag or an XPath,
  138. *namespaces* is an optional mapping from namespace prefix to full name.
  139. Return the first matching element, or None if no element was found.
  140. """
  141. return ElementPath.find(self, path, namespaces)
  142. def findtext(self, path, default=None, namespaces=None):
  143. 获取第一个寻找到的子节点的内容
  144. """Find text for first matching element by tag name or path.
  145. *path* is a string having either an element tag or an XPath,
  146. *default* is the value to return if the element was not found,
  147. *namespaces* is an optional mapping from namespace prefix to full name.
  148. Return text content of first matching element, or default value if
  149. none was found. Note that if an element is found having no text
  150. content, the empty string is returned.
  151. """
  152. return ElementPath.findtext(self, path, default, namespaces)
  153. def findall(self, path, namespaces=None):
  154. 获取所有的子节点
  155. """Find all matching subelements by tag name or path.
  156. *path* is a string having either an element tag or an XPath,
  157. *namespaces* is an optional mapping from namespace prefix to full name.
  158. Returns list containing all matching elements in document order.
  159. """
  160. return ElementPath.findall(self, path, namespaces)
  161. def iterfind(self, path, namespaces=None):
  162. 获取所有指定的节点,并创建一个迭代器(可以被for循环)
  163. """Find all matching subelements by tag name or path.
  164. *path* is a string having either an element tag or an XPath,
  165. *namespaces* is an optional mapping from namespace prefix to full name.
  166. Return an iterable yielding all matching elements in document order.
  167. """
  168. return ElementPath.iterfind(self, path, namespaces)
  169. def clear(self):
  170. 清空节点
  171. """Reset element.
  172. This function removes all subelements, clears all attributes, and sets
  173. the text and tail attributes to None.
  174. """
  175. self.attrib.clear()
  176. self._children = []
  177. self.text = self.tail = None
  178. def get(self, key, default=None):
  179. 获取当前节点的属性值
  180. """Get element attribute.
  181. Equivalent to attrib.get, but some implementations may handle this a
  182. bit more efficiently. *key* is what attribute to look for, and
  183. *default* is what to return if the attribute was not found.
  184. Returns a string containing the attribute value, or the default if
  185. attribute was not found.
  186. """
  187. return self.attrib.get(key, default)
  188. def set(self, key, value):
  189. 为当前节点设置属性值
  190. """Set element attribute.
  191. Equivalent to attrib[key] = value, but some implementations may handle
  192. this a bit more efficiently. *key* is what attribute to set, and
  193. *value* is the attribute value to set it to.
  194. """
  195. self.attrib[key] = value
  196. def keys(self):
  197. 获取当前节点的所有属性的 key
  198. """Get list of attribute names.
  199. Names are returned in an arbitrary order, just like an ordinary
  200. Python dict. Equivalent to attrib.keys()
  201. """
  202. return self.attrib.keys()
  203. def items(self):
  204. 获取当前节点的所有属性值,每个属性都是一个键值对
  205. """Get element attributes as a sequence.
  206. The attributes are returned in arbitrary order. Equivalent to
  207. attrib.items().
  208. Return a list of (name, value) tuples.
  209. """
  210. return self.attrib.items()
  211. def iter(self, tag=None):
  212. 在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
  213. """Create tree iterator.
  214. The iterator loops over the element and all subelements in document
  215. order, returning all elements with a matching tag.
  216. If the tree structure is modified during iteration, new or removed
  217. elements may or may not be included. To get a stable set, use the
  218. list() function on the iterator, and loop over the resulting list.
  219. *tag* is what tags to look for (default is to return all elements)
  220. Return an iterator containing all the matching elements.
  221. """
  222. if tag == "*":
  223. tag = None
  224. if tag is None or self.tag == tag:
  225. yield self
  226. for e in self._children:
  227. yield from e.iter(tag)
  228. # compatibility
  229. def getiterator(self, tag=None):
  230. # Change for a DeprecationWarning in 1.4
  231. warnings.warn(
  232. "This method will be removed in future versions. "
  233. "Use ‘elem.iter()‘ or ‘list(elem.iter())‘ instead.",
  234. PendingDeprecationWarning, stacklevel=2
  235. )
  236. return list(self.iter(tag))
  237. def itertext(self):
  238. 在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
  239. """Create text iterator.
  240. The iterator loops over the element and all subelements in document
  241. order, returning all inner text.
  242. """
  243. tag = self.tag
  244. if not isinstance(tag, str)以上是关于Python之路_Day7的主要内容,如果未能解决你的问题,请参考以下文章

    Python学习之路——Day7(面向对象)

    python自动化运维之路~DAY7

    Python之路,day7-Python基础

    python学习之路day7

    Python全栈之路Day7

    python 学习之路-day7