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) and tag is not None: 245 return 246 if self.text: 247 yield self.text 248 for e in self: 249 yield from e.itertext() 250 if e.tail: 251 yield e.tail
解析XML
1 <data> 2 <country name="Liechtenstein"> 3 <rank updated="yes">2</rank> 4 <year>2023</year> 5 <gdppc>141100</gdppc> 6 <neighbor direction="E" name="Austria" /> 7 <neighbor direction="W" name="Switzerland" /> 8 </country> 9 <country name="Singapore"> 10 <rank updated="yes">5</rank> 11 <year>2026</year> 12 <gdppc>59900</gdppc> 13 <neighbor direction="N" name="Malaysia" /> 14 </country> 15 <country name="Panama"> 16 <rank updated="yes">69</rank> 17 <year>2026</year> 18 <gdppc>13600</gdppc> 19 <neighbor direction="W" name="Costa Rica" /> 20 <neighbor direction="E" name="Colombia" /> 21 </country> 22 </data>
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 from xml.etree import ElementTree as ET 5 tree = ET.parse('xo.xml') 6 root = tree.getroot() 7 for child in root: 8 print(child.tag,child.attrib) 9 for gradechild in child: 10 print(gradechild.tag, gradechild.text)
修改节点内容:
由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 from xml.etree import ElementTree as ET 5 ############ 解析方式一 ############ 6 # 打开文件,读取XML内容 7 str_xml = open('xo.xml', 'r').read() 8 # 将字符串解析成xml特殊对象,root代指xml文件的根节点 9 root = ET.XML(str_xml) 10 ############ 操作 ############ 11 # 顶层标签 12 print(root.tag) 13 # 循环所有的year节点 14 for node in root.iter('year'): 15 # 将year节点中的内容自增一 16 new_year = int(node.text) + 1 17 node.text = str(new_year) 18 # 设置属性 19 node.set('name', 'alex') 20 node.set('age', '18') 21 # 删除属性 22 del node.attrib['name'] 23 ############ 保存文件 ############ 24 tree = ET.ElementTree(root) 25 tree.write("new_xml.xml", encoding='utf-8')
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 from xml.etree import ElementTree as ET 5 ############ 解析方式二 ############ 6 # 直接解析xml文件 7 tree = ET.parse("xo.xml") 8 # 获取xml文件的根节点 9 root = tree.getroot() 10 ############ 操作 ############ 11 # 顶层标签 12 print(root.tag) 13 # 循环所有的year节点 14 for node in root.iter('year'): 15 # 将year节点中的内容自增一 16 new_year = int(node.text) + 1 17 node.text = str(new_year) 18 # 设置属性 19 node.set('name', 'alex') 20 node.set('age', '18') 21 # 删除属性 22 del node.attrib['name'] 23 ############ 保存文件 ############ 24 tree.write("new_xml.xml", encoding='utf-8')
创建XML文档
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 from xml.etree import ElementTree as ET 5 # 创建根节点 6 root = ET.Element("famliy") 7 # 创建节点大儿子 8 son1 = ET.Element('son', {'name': '儿1'}) 9 # 创建小儿子 10 son2 = ET.Element('son', {"name": '儿2'}) 11 # 在大儿子中创建两个孙子 12 grandson1 = ET.Element('grandson', {'name': '儿11'}) 13 grandson2 = ET.Element('grandson', {'name': '儿12'}) 14 son1.append(grandson1) 15 son1.append(grandson2) 16 # 把儿子添加到根节点中 17 root.append(son1) 18 root.append(son1) 19 tree = ET.ElementTree(root) 20 tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 from xml.etree import ElementTree as ET 5 from xml.dom import minidom 6 def prettify(elem): 7 """将节点转换成字符串,并添加缩进。 8 """ 9 rough_string = ET.tostring(elem, 'utf-8') 10 reparsed = minidom.parseString(rough_string) 11 return reparsed.toprettyxml(indent=" ") 12 # 创建根节点 13 root = ET.Element("famliy") 14 # 创建大儿子 15 # son1 = ET.Element('son', {'name': '儿1'}) 16 son1 = root.makeelement('son', {'name': '儿1'}) 17 # 创建小儿子 18 # son2 = ET.Element('son', {"name": '儿2'}) 19 son2 = root.makeelement('son', {"name": '儿2'}) 20 # 在大儿子中创建两个孙子 21 # grandson1 = ET.Element('grandson', {'name': '儿11'}) 22 grandson1 = son1.makeelement('grandson', {'name': '儿11'}) 23 # grandson2 = ET.Element('grandson', {'name': '儿12'}) 24 grandson2 = son1.makeelement('grandson', {'name': '儿12'}) 25 son1.append(grandson1) 26 son1.append(grandson2) 27 # 把儿子添加到根节点中 28 root.append(son1) 29 root.append(son1) 30 raw_str = prettify(root) 31 f = open("xxxoo.xml",'w',encoding='utf-8') 32 f.write(raw_str) 33 f.close()
3、shutil
高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中
1 import shutil 2 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
shutil.copyfile(src, dst)
拷贝文件
1 shutil.copyfile('f1.log', 'f2.log')
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
1 shutil.copymode('f1.log', 'f2.log')
shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
1 shutil.copystat('f1.log', 'f2.log')
shutil.copy(src, dst)
拷贝文件和权限
1 import shutil 2 shutil.copy('f1.log', 'f2.log')
shutil.copy2(src, dst)
拷贝文件和状态信息
1 import shutil 2 shutil.copy2('f1.log', 'f2.log')
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
1 import shutil 2 3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
1 import shutil 2 shutil.rmtree('folder1')
shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。
1 import shutil 2 shutil.move('folder1', 'folder3')
shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
- base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径
- 如:www =>保存至当前路径
- 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
- format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要压缩的文件夹路径(默认当前目录)
- owner: 用户,默认当前用户
- group: 组,默认当前组
- logger: 用于记录日志,通常是logging.Logger对象
1 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录 2 import shutil 3 ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') 4 5 6 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录 7 import shutil 8 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
zipfile
处理zip文件的模块
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 import zipfile 5 # 压缩文件 6 z = zipfile.ZipFile('test_zip.zip', 'w') 7 z.write('conf') 8 z.write('config.py') 9 z.close() 10 # 解压文件 11 z = zipfile.ZipFile('test_zip.zip', 'r') 12 # z.extractall() # 解压全部文件 13 for item in z.namelist(): 14 print(item) 15 z.extract('conf') # 解压单个文件 16 z.close()
tarfiel
处理tar文件的模块
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 import tarfile 5 # 压缩 6 tar = tarfile.open('test_tar.tar','w') 7 tar.add("E:\Python\oldboy_py\Day7\xml_1.py", arcname='xml_test1.py') 8 tar.add("E:\Python\oldboy_py\Day7\xml_2.py", arcname='xml_test2.py') 9 tar.close() 10 # 解压 11 tar = tarfile.open('test_tar.tar','r') 12 tar.extractall() # 可设置解压地址,全部解压 13 for item in tar.getmembers(): 14 print(item) 15 obj = tar.getmember('xml_test1.py') 16 tar.extract(obj) 17 tar.close()
4、系统命令subprocess
可以执行shell命令的相关模块和函数有:
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 import subprocess 5 # call 6 # 执行命令,返回状态码 7 ret = subprocess.call(["ls", "-l"], shell=False) 8 ret = subprocess.call("ls -l", shell=True) 9 # check_call 10 # 执行命令,如果执行状态码是 0 ,则返回0,否则抛异常 11 subprocess.check_call(["ls", "-l"]) 12 subprocess.check_call("exit 1", shell=True) 13 # check_output 14 # 执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常 15 subprocess.check_output(["echo", "Hello World!"]) 16 subprocess.check_output("exit 1", shell=True)
subprocess.Popen(...)
用于执行复杂的系统命令
参数:
- args:shell命令,可以是字符串或者序列类型(如:list,元组)
- bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
- close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
- shell:同上
- cwd:用于设置子进程的当前目录
- env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
- universal_newlines:不同系统的换行符不同,True -> 同意使用
- startupinfo与createionflags只在windows下有效
- 将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 import subprocess 5 # 创建文件夹 6 ret1 = subprocess.Popen(["mkdir","t1"]) 7 ret2 = subprocess.Popen("mkdir t2", shell=True) 8 obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
终端输入的命令分为两种:
- 输入即可得到输出,如:ifconfig
- 输入进行某环境,依赖再输入,如:python
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 import subprocess 5 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 6 obj.stdin.write("print(1) ") 7 obj.stdin.write("print(2)") 8 obj.stdin.close() 9 cmd_out = obj.stdout.read() 10 obj.stdout.close() 11 cmd_error = obj.stderr.read() 12 obj.stderr.close() 13 print(cmd_out) 14 print(cmd_error) 15 # 第二种方法 16 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 17 obj.stdin.write("print(1) ") 18 obj.stdin.write("print(2)") 19 out_error_list = obj.communicate() 20 print(out_error_list) 21 # 第三种方法 22 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 23 out_error_list = obj.communicate('print("hello")') 24 print(out_error_list)
二、面向对象(上)
什么时候用面向对象?当某一些函数具有相同参数是,可以使用面向对象的方式,将参数值一次性的封装到对象,以后去对象中取值即可。
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 # 面向对象 5 class SQLHelper: 6 def fetch(self,sql): 7 print(self.hhost) 8 print(self.uuser) 9 print(self.ppwd) 10 print(sql) 11 def create(self,sql): 12 print(sql) 13 def remove(self,id): 14 print(id) 15 def modify(self,name): 16 print(name) 17 obj = SQLHelper() 18 obj.hhost = "www.test.com" # 封装参数 19 obj.uuser = "sandler" 20 obj.ppwd = "1234" 21 obj.fetch('select * from a;')
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 # 面向对象 5 class SQLHelper: 6 def __init__(self,host,user,pwd): 7 self.hhost = host # 封装参数 8 self.uuser = user 9 self.ppwd = pwd 10 def fetch(self,sql): 11 print(self.hhost) 12 print(self.uuser) 13 print(self.ppwd) 14 print(sql) 15 def create(self,sql): 16 print(sql) 17 def remove(self,id): 18 print(id) 19 def modify(self,name): 20 print(name) 21 obj1 = SQLHelper("www.test.com","sandler",1234) 22 obj2 = SQLHelper("www.test2.com","sandler",2345) 23 obj1.fetch('select * from a;')
面向对象三大特性:封装,继承,多态
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 class c1: 5 def __init__(self,name,obj): 6 self.name = name 7 self.obj = obj 8 class c2: 9 def __init__(self,name,age): 10 self.name = name 11 self.age = age 12 def show(self): 13 print(self.name) 14 c2_obj = c2('aa' , 11) 15 c1_obj = c1('alex',c2_obj) 16 print(c1_obj.obj.age) 17 print(c1_obj.obj.name) 18 print(c1_obj.name)
封装
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 # 面向对象 5 class c1: 6 def __init__(self,name,obj): 7 self.name = name 8 self.obj = obj 9 class c2: 10 def __init__(self,name,age): 11 self.name = name 12 self.age = age 13 def show(self): 14 print(self.name) 15 class c3: 16 def __init__(self,a1): 17 self.money = 123 18 self.aaa = a1 19 c2_obj = c2('aa' , 11) 20 # c2_obj是c2类型 21 # - name = 'aa' 22 # - age = 11 23 c1_obj = c1('alex',c2_obj) 24 # c1_obj是c1类型 25 # - name = 'alex' 26 # - obj = c2_obj 27 c3_obj = c3(c1_obj) 28 # c3_obj是c3类型 29 # - money = 123 30 # - aaa = c1_obj 31 # 通过c3_obj输出c2内的name 32 print(c3_obj.aaa.obj.name) 33 # 通过c3_obj输出c2内的show方法 34 print(c3_obj.aaa.obj.show())
继承
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By sandler 4 # 类的继承 5 class F1: 6 def show(self): 7 print('show') 8 def foo(self): 9 print(self.name) 10 class F2(F1): 11 def __init__(self,name): 12 self.name = name 13 def bar(self): 14 print('bar') 15 obj = F2('yuli') 16 obj.foo()
多继承(混乱的继承关系)
作业
选课系统
思路:
管理员:
1、创建老师(爱好,姓名,年龄,资产=0)
class Teacher:
def __init__(self,favor,name,age)
self.favor = favor
self.name = name
self.age = age
self.asset = 0
obj1 = Teacher(...)
obj2 = Teacher(...)
[obj1,obj2,...]
pickle.dump(文件)
2、创建课程()
课程类:
-课程名
-课时费
-负责老师 = obj1
功能:
-上课
--返回课程内容
--负责老师挣钱
学生:
类:
学生》选课
__init__
选课=[课程对象]
上课:
选课
1、生物课
课程对象上课()
鸡汤
电影推荐
PS:之前不小心把第七天笔记删除了,现在补上!