Python开发【第⑤篇】:面向对象

shutil

尖端的公文、文件夹、压缩包处理模块。

shutil.copyfileobj(ferc,fdst[,length])

将文件内容拷贝到另3个文本中

  1. import shutil

  2.  

  3. shutil.copyfileobj(open(‘old.xml’,’r’),open(‘new.xml’,’w’))

shuit.copyfile(src,dst)

拷贝文件

  1. shutil.copyfile(‘f1.log’,’f2.log’)

zipfile、tarfile

zipfile创造压缩包

  1. import zipfile

  2.  

  3. #压缩

  4. z = zipfile.ZipFile(‘test.zip’,’a’)

  1. z.write(‘new.xml’)

  2. z.write(‘family.xml’)

  3. z.close

zipfile解压压缩包

  1. #解压

  2. z = zipfile.ZipFile(‘test.zip’,’r’)

  1.  

  2. #解压全体

  3. # z.extractall()

  4.  

  5. #解压单个文件

  6. z.extract(“new.xml”)

  7.  

  8. #获得压缩包的积极分子

  9. for
    item in z.namelist():

  10.     print(item)

  11.  

  12. z.close()

tarfile创设压缩包

  1. import tarfile

  2.  

  3. #压缩

  4. tar = tarfile.open(“test.tar”,’w’)

  5. #arcname重命名

  6. tar.add(‘test.py’,arcname=’test_1.py’)

  1. tar.add(‘xml_test.py’,arcname=’xml_test.py’)
  1. tar.close()

tarfile解压压缩包

  1. tar = tarfile.open(‘test.tar’,’r’)
  1.  

  2. #可安装解压路径

  3. # tar.extractall()

  4.  

  5. for
    item in tar.getmembers():

  6.     print(item,type(item))

  7.  

  8. obj = tar.getmember(“test_1.py”)

  9. print(obj,type(obj))

  10. tar.extract(obj)

  11.  

  12. tar.close()

check_call

执行命令,即使实施情形码是0,则重返0,不然抛出相当。

  1. ret = subprocess.check_call(“ls -l”,shell=True)

check_output

执行命令,如若情形码是0,则赶回执行结果,不然抛出卓殊。

  1. ret = subprocess.check_output(“ls -l”,shell=True)

系统命令

多继承

  1. class
    C1:

  2.     def f1(self):

  3.         pass

  4.  

  5. class
    C2:

  6.     def f2(self):

  7.         pass

  8.  

  9. class
    C3(C2,C1):

  10.     pass

  11.  

  12. obj = C3()

 

  1. class
    C1:

  2.     def f1(self):

  3.         print(“C1.f1()”)

  4.  

  5. class
    C2:

  6.     def f1(self):

  7.         print(“C2.f1()”)

  8.  

  9. class
    C3(C2,C1):

  10.     pass

  11.  

  12. obj = C3()

  13. obj.f1()

  14. 输出:

  15. C2.f1()

 

  1. class
    C0:

  2.     def f1(self):

  3.         print(“C0.f1()”)

  4.  

  5. class
    C1():

  6.     def f1(self):

  7.         print(“C1.f1()”)

  8.  

  9. class
    C2(C0):

  10.     def f2(self):

  11.         print(“C2.f1()”)

  12.  

  13. class
    C3(C2,C1):

  14.     pass

  15.  

  16. obj = C3()

  17. obj.f1()

  18. 输出:

  19. C0.f1()

 

  1. class
    C_2:

  2.     def f1(self):

  3.         print(“C_2.f1()”)

  4.  

  5. class
    C_1(C_2):

  6.     def f1(self):

  7.         print(“C_1.f1()”)

  8.  

  9. class
    C0(C_2):

  10.     def f2(self):

  11.         print(“C0.f1()”)

  12.  

  13. class
    C1(C_1):

  14.     def f1(self):

  15.         print(“C1.f1()”)

  16.  

  17. class
    C2(C0):

  18.     def f2(self):

  19.         print(“C2.f1()”)

  20.  

  21. class
    C3(C2,C1):

  22.     pass

  23.  

  24. obj = C3()

  25. obj.f1()

  26. 输出:

  27. C1.f1()

封装

面向对象的次序设计中,有些类把所急需的数量(类的性质)和对数码的操作(类的行事)全体都封装在类中,分小名为类的成员变量和艺术(成员函数)。那种把成员变量和成员函数封装在联合署名的编制程序脾性称为封装。

  1. class
    c1:

  2.     def __init__(self,name,obj):

  1.         self.name = name

  2.         self.obj = obj

  3.  

  4. class
    c2:

  5.     def __init__(self,name,age):

  1.         self.name = name

  2.         self.age = age

  3.  

  4.     def show(self):

  5.         print(self.name)

  6.  

  7. class
    c3:

  8.     def __init__(self,a1):

  9.         self.money = 123

  10.         self.aaa = a1

  11.  

  12.  

  13. c2_obj = c2(‘aa’,11)

  14.  

  15. c1_obj = c1(“alex”,c2_obj)

  16. print(c1_obj.obj.age)

  17.  

  18. c3_obj = c3(c1_obj)

  19. print(c3_obj.aaa.obj.age)

  20. 输出:

  21. 11

  22. 11

此起彼伏总结

对于接二连三其艺术(属性)恐怕定义在近日类,也说不定出自于基类,所以在艺术调用时就供给对当下类和基类进行检索以明确方法所在的职位。而搜索的一一正是所谓的措施分析顺序(MRO、Method
Resolution
Order)。对于单继承来说,MRO一般比较简单,而对此多连续来说,MRO比较复杂。下边就二种基本的延续方式解析。

图片 1

图片 2

什么日期利用面向对象?

当一些函数具有同等参数时,能够接纳面向对象的章程,将参数值一回性打包到对象中,方便现在去对象中取值。

单继承

  1. class
    F1:#父类、基类

  2.     def show(self):

  3.         print(‘show’)

  4.  

  5. #F2继承F1

  6. class
    F2(F1):#子类、派生类

  7.     def bar(self):

  8.         print(‘bar’)

  9.  

  10. obj = F2()

  11. obj.bar()

  12. obj.show()

  13. 输出:

  14. bar

  15. show

 

  1. class
    F1:#父类、基类

  2.     def show(self):

  3.         print(‘show’)

  4.  

  5.     def foo(self):

  6.         print(self.name)

  7.  

  8. #F2继承F1

  9. class
    F2(F1):#子类、派生类

  10.     def __init__(self,name):

  1.         self.name = name

  2.  

  3.     def bar(self):

  4.         print(‘bar’)

  5.  

  6.     def show(self):#投机的预先级更高

  1.         print(‘F2 show’)

  2.  

  3. obj = F2(‘alex’)

  4. obj.bar()

  5. obj.show()

  6. obj.foo()

  7. 输出:

  8. bar

  9. F2 show

  10. alex

 

  1. class
    S1:

  2.     def F1(self):

  3.         self.F2()

  4.  

  5.     def F2(self):

  6.         print(‘S1.F2()’)

  7.  

  8. class
    S2(S1):

  9.     def F3(self):

  10.         self.F1()

  11.  

  12.     def F2(self):

  13.         print(‘S2.F2()’)

  14.  

  15. obj = S2()

  16. obj.F3()

  17. 输出:

  18. S2.F2()

函数式编制程序和面向对象编制程序达成发送邮件功效。

函数达成:

  1. def mail(email,message):

  2.     print(“发送”)

  3.    return True

  4.  

  5. mail(“xxxx.@126.com”,”hello”)

面向对象完毕:

  1. class
    Foo:

  2.     #方法

  3.    def mail(self,email,message):

  1.        print(“发送”)

  2.       return True

  3.  

  4. #调用

  5. #壹 、成立对象,类名()

  6. obj = Foo()

  7. #二 、通过对象去履行措施

  8. obj.mail(“xxxx.@126.com”,”hello”)

继承

继续是四个类或几个类之间的父子关系,子进度继续父进度的装有国有实例变量和艺术。继承达成了代码的选定。重用已经存在的多寡和行为,减少代码的重新编写,python在类名后用一对圆括号表示继续关系,括号中的类表示父类,假设父类定义了__init__格局,则子类必须出示地调用父类的__init__主意,假如子类供给增添父类的行事,能够增加__init__艺术的参数。

call

取得状态码,0符合规律。

  1. import subprocess

  2.  

  3. #shell=False命令传入格局为列表

  4. ret = subprocess.call([“ls”,”-l”],shell=False)

  5.  

  6. #shell=True命令传入形式为字符串

  1. ret = subprocess.call(“ls -l”,shell=True)

构造方法

类中有一个尤其的办法__init__,类()自动被执行。

  1. class
    SQLHelper:

  2.     def __init__(self,a1,a2,a3):

  1.         self.hhost = a1

  2.         self.uusername = a2

  3.         self.passwd = a3

  4.         print(“自动执行init”)

  5.     def fetch(self, sql):

  6.         #链接数据库

  7.         print(self.hhost)

  8.         print(self.uusername)

  9.         print(self.passwd)

  10.         print(sql)

  11.     def create(self,sql):

  12.         pass

  13.     def remove(self,nid):

  14.         pass

  15.     def modify(self,name):

  16.         pass

  17. obj1 = SQLHelper(“1xxx.xxx.xxx”,”xxxx”,”xxxx”)

  18. obj1.fetch(“select * from A”)

  19. obj2 = SQLHelper(“2xxx.xxx.xxx”,”xxxx”,”xxxx”)

  20. obj2.fetch(“select * form A”)

  21. 输出:

  22. 电动执行init

  23. 1xxx.xxx.xxx

  24. xxxx

  25. xxxx

  26. select * from A

  27. 活动执行init

  28. 2xxx.xxx.xxx

  29. xxxx

  30. xxxx

  31. select * form A

面向对象三大特征:封装、继承、多态。

configparser模块

configparser用于拍卖特定格式的文书,其本质是选用open来操作文件。

文件a.txt

  1. [section1]

  2. k1 = 123

  3. k2:v2

  4.  

  5. [section2]

  6. k1 = 234

加载文件a.txt

  1. import configparser

  2.  

  3. config = configparser.ConfigParser()

  1. config.read(‘a.txt’,encoding=’utf-8′)

对文本有关操作

  1. import configparser

  2.  

  3. config = configparser.ConfigParser()

  1. config.read(‘a.txt’,encoding=’utf-8′)
  1.  

  2. #获得具有节点

  3. ret = config.sections()

  4. print(ret)

  5.  

  6. #获取钦点节点下的享有键值对

  7. ret = config.items(‘section1’)

  8. print(ret)

  9.  

  10. #取得内定节点下具有的键

  11. ret = config.options(‘section1’)

  1. print(ret)

  2.  

  3. #获得钦命节点下钦命key的值

  4.  

  5. ret = config.get(‘section1′,’k1’)

  6. #转换成int

  7. # ret = config.getint(‘section1′,’k1’)

  1. #转换成float

  2. # ret =
    config.getfloat(‘section1′,’k1’)

  3. #转换成boolean

  4. # ret =
    config.getboolean(‘section1′,’k1’)

  5.  

  6. print(ret)

  7.  

  8. #反省、删除、设置钦点组内的键值对

  1.  

  2. #检查

  3. has_opt =
    config.has_option(‘section1’)

  4. print(has_opt)

  5.  

  6. #添加节点

  7. config.add_section(‘SEC_1’)

  8. config.write(open(‘a.txt’,’w’))

  9.  

  10. #去除节点

  11. config.remove_section(‘SEC_1’)

  1. config.write(open(‘a.txt’,’w’))

  2.  

  3. #检查、删除、设置钦点组内的键值对

  1.  

  2. #检查

  3. has_opt =
    config.has_option(‘section1′,’k1’)

  4. print(has_opt)

  5.  

  6. #删除

  7. config.remove_option(‘section1′,’k1’)

  1. config.write(open(‘a.txt’,’w’))

  2.  

  3. #设置

  4. config.set(‘section1′,’k10′,’123’)

  5. config.write(open(‘a.txt’,’w’))

self是什么?

self是一个python自动传值的参数,那么些目的执行措施,self正是什么人。

obj1 = SQLHelper()

obj1.hhost = “1xxx.xxx.xxx”

obj1.uusername = “xxxx”

obj1.passwd = “xxxx”

obj1.fetch(“sql”) #self==obj1

 

obj2 = SQLHelper()

obj2.hhost = “2xxx.xxx.xxx”

obj2.uusername = “xxxx”

obj2.passwd = “xxxx”

obj2.fetch(“sql”) #self==obj2

类和目的

1、创建类:

class 类名:

def 方法名(self,xxx):

pass

② 、创设对象

对象 = 类名()

③ 、通过对象进行办法

对象.方法名(xxx)

函数式

def fetch(host,username,passwd,sql):

pass

def create(host,username,passwd,sql):

pass

def remove(host,username,passwd,sql):

pass

def modify(host,username,passwd,sql):

pass

fetch(…)

面向对象:

class SQLHelper:

def fetch(self,host,username,passwd,sql):

pass

def create(self,host,username,passwd,sql):

pass

def remove(self,host,username,passwd,nid):

pass

def modify(self,host,username,passwd,name):

pass

obj = SQLHelper()

obj.fetch(…)

面向对象优化:

class SQLHelper:

def fetch(self, sql):

pass

def create(self,sql):

pass

def remove(self,nid):

pass

def modify(self,name):

pass

obj = SQLHelper()

obj.hhost = “xxx.xxx.xxx”

obj.uusername = “xxxx”

obj.passwd = “xxxx”

obj.fetch(“sql”)

  1. class
    SQLHelper:

  2.     def fetch(self, sql):

  3.         #链接数据库

  4.         print(self.hhost)

  5.         print(self.uusername)

  6.         print(self.passwd)

  7.         print(sql)

  8.     def create(self,sql):

  9.         pass

  10.     def remove(self,nid):

  11.         pass

  12.     def modify(self,name):

  13.         pass

  14. obj = SQLHelper()

  15. obj.hhost = “xxx.xxx.xxx”

  16. obj.uusername = “xxxx”

  17. obj.passwd = “xxxx”

  18. obj.fetch(“select * from A”)

  19. 输出:

  20. xxx.xxx.xxx

  21. xxxx

  22. xxxx

  23. select * from A

xml相关操作

解析xml文件

  1. from xml.etree import ElementTree as ET

  2. #一向解析xml文件

  3. tree = ET.parse(‘xml_test.xml’)

  1.  

  2. #赢得xml文件的根节点

  3. root = tree.getroot()

  4. print(root)

  5. print(root.tag)

  6. print(root.attrib)

  7. “””

  8. 输出:

  9. <Element ‘data’ at
    0x00000000006D0688>

  10. data

  11. {‘title_2’: ‘test_2’, ‘title_1’:
    ‘test_1’}

  12. “””

浅析字符串

  1. from xml.etree import ElementTree as ET

  2.  

  3. #开辟文件,读取xml内容

  4. str_xml =
    open(‘xm_test.xml’,’r’).read()

  5.  

  6. #将字符串解析成xml特殊对象,root代指xml文件的根节点

  1. root = ET.XML(str_xml)

遍历xml文书档案的富有剧情

  1. from xml.etree import ElementTree as ET

  2. #直接解析xml文件

  3. tree = ET.parse(‘xml_test.xml’)

  1.  

  2. #得到xml文件的根节点

  3. root = tree.getroot()

  4. #遍历xml文书档案的第②层

  5. for
    child in root:

  6.     #第壹层节点的标签名称和标签属性

  1.     print(child.tag,child.attrib)
  1.     #遍历xml文书档案的第1层

  2.     for i in
    child:

  3.         #其三层节点的竹签名称和剧情

  1.         print(i.tag,i.text)

  2. “””

  3. 输出:

  4. country {‘name’: ‘Liechtenstenin’}

  1. rank 2

  2. year 2023

  3. gdppc 141100

  4. neighbor None

  5. neighbor None

  6. country {‘name’: ‘Sinagapore’}

  7. rank 5

  8. year 2026

  9. gdppc 59900

  10. neighbor None

  11. country {‘name’: ‘Panama’}

  12. rank 69

  13. year 2026

  14. gdppc 13600

  15. neighbor None

  16. neighbor None

  17. “””

修改xml

解析字符串格局开始展览改动

  1. from xml.etree import ElementTree as ET

  2. str_xml =
    open(‘xml_test.xml’,’r’).read()

  3. root = ET.XML(str_xml)

  4.  

  5. #赢得顶层标签

  6. print(root.tag)

  7.  

  8. #循环全部的year节点

  9. for
    node in root.iter(‘year’):

  10.     #将year节点中的内容自增一

  11.     new_year = int(node.text) + 1

  12.     node.text = str(new_year)

  13.  

  14.     #安装属性

  15.     node.set(‘name’,’alex’)

  16.     node.set(‘age’,’19’)

  17.  

  18.     #剔除属性

  19.     del node.attrib[‘name’]

  20.  

  21. #履新文件

  22. tree = ET.ElementTree(root)

  23. tree.write(“new_xml_test.xml”,encoding=’utf-8′)

浅析文件格局开始展览改动

直白调用tree.write写入即可。

  1. from xml.etree import ElementTree as ET

  2. tree = ET.parse(‘xml_test.xml’)

  1. root = tree.getroot()

  2.  

  3. “””

  4. 操作

  5. “””

  6.  

  7. #创新文件

  8. tree.write(“new_xml_test2.xml”,encoding=’utf-8′)

添加节点

  1. from xml.etree import ElementTree as ET

  2. tree = ET.parse(‘xml_test.xml’)

  1. root = tree.getroot()

  2.  

  3. ele = ET.Element(‘Alex’,{‘k1′:’v1’})

  1. ele.text = “test”

  2. root.append(ele)

  3.  

  4. tree.write(“new.xml”,encoding=’utf-8′)

结果new.xml:

  1. <data title_1=”test_1″ title_2=”test_2″>

  2.  

  3. “””

  4. 原内容

  5. “””

  6.  

  7. <Alex k1=”v1″>test</Alex></data>

出于原生保存xml时暗中同意无缩进,纵然要设置缩进需求修改保存方法。

  1. from xml.etree import ElementTree as ET

  2. from xml.dom import minidom

  3.  

  4. def prettify(elem):

  5.     “””

  6.     将节点转换到字符串,并添加缩进

  1.     :param elem:

  2.     :return:

  3.     “””

  4.     rough_string =
    ET.tostring(elem,’utf-8′)

  5.     reparsed =
    minidom.parseString(rough_string)

  6.     return reparsed.toprettyxml(indent=”\t”)

  7.  

  8. #开创根节点

  9. root = ET.Element(“family”)

  10.  

  11. #创办大孙子

  12. # son1 =
    ET.Element(‘son’,{‘name’:’儿1′})

  13. son1 =
    root.makeelement(‘son’,{‘name’:’儿1′})

  14. #创立小外孙子

  15. # son2 =
    ET.Element(‘son’,{‘name’:’儿2′})

  16. son2 =
    root.makeelement(‘son’,{‘name’:’儿2′})

  17.  

  18. #在孙子中开创二个外孙子

  19. # grandson1 =
    ET.Element(‘grandson’,{‘name’:’儿11′})

  20. grandson1 =
    root.makeelement(‘grandson’,{‘name’:’儿11′})

  21. # grandson2 =
    ET.Element(‘grandon’,{‘name’:’儿12′})

  22. grandson2 =
    root.makeelement(‘grandon’,{‘name’:’儿12′})

  23.  

  24. son1.append(grandson1)

  25. son2.append(grandson2)

  26.  

  27. #把外甥添加到根节点

  28. root.append(son1)

  29. root.append(son2)

  30.  

  31. raw_str = prettify(root)

  32.  

  33. f =
    open(‘family.xml’,’w’,encoding=’utf-8′)

  34. f.write(raw_str)

  35. f.close()

family.xml:

  1. <?xml version=”1.0″ ?>

  2. <family>

  3.    <son name=”儿1″>

  4.       <grandson name=”儿11″/>

  5.    </son>

  6.    <son name=”儿2″>

  7.       <grandon name=”儿12″/>

  8.    </son>

  9. </family>

XML模块

xml是兑现差异语言或程序之间展开数据交流的情商。

文件xml_text.xml

  1. <data>

  2.     <country name=”Liechtenstenin”>

  3.         <rank update=”yes”>2</rank>

  4.         <year>2023</year>

  1.         <gdppc>141100</gbppc>
  1.         <neighbor direction=”E” name=”Austria”/>

  2.         <neighbor direction=”W” name=”Switzerland”/>

  3.     </country>

  4.     <country name=”Sinagapore”>

  5.         <rank update=”yes”>5</rank>

  6.         <year>2026</year>

  1.         <gdppc>59900</gdppc>
  1.         <neighbor direction=”N” name=”Malaysia”/>

  2.     </country>

  3.     <country name=”Panama”>

  4.         <rank update=”yes”>69</rank>

  5.         <year>2026</year>

  1.         <gdppc>13600</gdppc>
  1.         <neighbor direction=”W” name=”Costa Rica”/>

  2.         <neighbor direction=”E” name=”Costa Rica”/>

  3.     </country>

  4. </data>