python-学习 补充模块;面向对象程序设计

一、模块补充

  1. configparser模块

 1 import configparser
 2 
 3 config=configparser.ConfigParser()
 4 config.read('a.ini')
 5 
 6 #读取配置
 7 print(config.sections()) #看标题
 8 print(config.options(config.sections()[0])) #查看某个标题下的配置项
 9 res=config.get('alex','name')#查看某个标题下的某个配置项的值
10 print(type(res))
11 
12 res1=config.getint('egon','age')#查看某个标题下的某个配置项的值
13 print(type(res1))
14 
15 res1=config.getboolean('egon','is_admin')#查看某个标题下的某个配置项的值
16 print(type(res1))
17 
18 res1=config.getfloat('egon','salary')#查看某个标题下的某个配置项的值
19 print(type(res1))
20 
21 
22 #修改
23 # config.remove_section('alex')
24 # config.remove_option('egon','age')
25 
26 config.add_section('alex')
27 config.set('alex','name','SB')
28 
29 
30 config.write(open('a.ini','w'))
例子
1 [egon]
2 name = egon
3 is_admin = True
4 salary = 3.1
5 
6 [alex]
7 name = SB
a.ini

  更多详细例子

 [DEFAULT]
 ServerAliveInterval = 45
 Compression = yes
 CompressionLevel = 9
 ForwardX11 = yes
   
 [bitbucket.org]
 User = hg
    
 [topsecret.server.com]
 Port = 50022
 ForwardX11 = no
View Code
 php.ini文件的格式也是如翠

1 获取所有节点

import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res=config.sections()
print(res)

'''
打印结果:
['bitbucket.org', 'topsecret.server.com']
'''
View Code

2 获取指定节点下所有的键值对

import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res=config.items('bitbucket.org')
print(res)

'''
打印结果:(包含DEFAULT以及bitbucket.org这俩标题下所有的items)
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
'''
View Code

3 获取指定节点下所有的建

import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res=config.options('bitbucket.org')
print(res)

'''
打印结果:(包含DEFAULT以及bitbucket.org这俩标题下所有的键)
['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']'''
View Code

4 获取指定节点下指定key的值

import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res1=config.get('bitbucket.org','user')

res2=config.getint('topsecret.server.com','port')
res3=config.getfloat('topsecret.server.com','port')
res4=config.getboolean('topsecret.server.com','ForwardX11')

print(res1)
print(res2)
print(res3)
print(res4)

'''
打印结果:
hg
50022
50022.0
False
'''
View Code

5 检查、删除、添加节点

import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')

#检查
has_sec=config.has_section('bitbucket.org')
print(has_sec) #打印True

#添加节点
config.add_section('egon') #已经存在则报错
config['egon']['username']='gangdan'
config['egon']['age']='18'
config.write(open('test.ini','w'))

#删除节点
config.remove_section('egon')
config.write(open('test.ini','w'))
View Code 

6 检查、删除、设置指定组内的键值对

import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')

#检查
has_sec=config.has_option('bitbucket.org','user') #bitbucket.org下有一个键user
print(has_sec) #打印True

#删除
config.remove_option('DEFAULT','forwardx11')
config.write(open('test.ini','w'))

#设置
config.set('bitbucket.org','user','gangdang')
config.write(open('test.ini','w'))
View Code
 基于上述方法添加一个ini文档

2.hashlib模块

 三个特点:
1.内容相同则hash运算结果相同,内容稍微改变则hash值则变
2.不可逆推
3.相同算法:无论校验多长的数据,得到的哈希值长度固定。

 1 import hashlib
 2 
 3 m=hashlib.md5()
 4 m.update('hello'.encode('utf-8'))
 5 m.update('world'.encode('utf-8'))
 6 print(m.hexdigest())
 7 
 8 
 9 m=hashlib.md5()
10 m.update('helloworld'.encode('utf-8'))
11 print(m.hexdigest())
12 
13 m=hashlib.md5('helloworld'.encode('utf-8'))
14 print(m.hexdigest())
15 
16 
17 m=hashlib.md5('h'.encode('utf-8'))
18 m.update('elloworld'.encode('utf-8'))
19 print(m.hexdigest())
20 m=hashlib.md5()
21 with open('a.xml','rb') as f:
22     for line in f:
23         m.update(line)
24 print(m.hexdigest())
例子
1 #加盐
2 password='alex3714'
3 m=hashlib.md5('yihangbailushangqingtian'.encode('utf-8'))
4 m.update(password.encode('utf-8'))
5 
6 passwd_md5=m.hexdigest()
7 
8 print(passwd_md5)
加盐例子

python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密:

 1 import hmac
 2 
 3 h=hmac.new('hello'.encode('utf-8'))
 4 h.update('world'.encode('utf-8'))
 5 print(h.hexdigest())
 6 
 7 h=hmac.new('hello'.encode('utf-8'))
 8 h.update('w'.encode('utf-8'))
 9 h.update('or'.encode('utf-8'))
10 h.update('ld'.encode('utf-8'))
11 print(h.hexdigest())
例子

3.subprocess模块

创建子进程   详细参考官网

 1 import subprocess
 2 
 3 # res=subprocess.Popen(r'dir D:4-视频录制存放目录python18期day7xml模块',
 4 #                      shell=True,
 5 #                      stdout=subprocess.PIPE,
 6 #                      stderr=subprocess.PIPE)
 7 # # print('=================>',res)
 8 # # print('-========>',res.stdout.read())
 9 # print('-========>',res.stderr.read().decode('gbk'))
10 # print('-========>',res.stderr.read().decode('gbk'))
11 # print('-========>',res.stderr.read().decode('gbk'))
12 # print('-========>',res.stderr.read().decode('gbk'))
13 
14 
15 #dir file_path | findstr xml$
16 res1=subprocess.Popen(r'dir D:4-视频录制存放目录python18期day7xml模块',
17                      shell=True,
18                      stdout=subprocess.PIPE,)
19 
20 # stdin=res1.stout
21 res2=subprocess.Popen(r'findstr xml$',
22                      shell=True,
23                      stdin=res1.stdout,
24                      stdout=subprocess.PIPE,)
例子

4.xml模块

import xml.etree.ElementTree as ET
tree=ET.parse('a.xml')
root=tree.getroot()

for child in root:
    print('====>',child.tag)
    for i in child:
        print(i.tag,i.attrib,i.text)

#查找element元素的三种方式
years=root.iter('year') #扫描整个xml文档树,找到所有
for i in years:
    print(i)

res1=root.find('country') #谁来调,就从谁下一层开始找,只找一个
print(res1)

res2=root.findall('country') #谁来调,就从谁下一层开始找,只找一个
print(res2)


#修改
years=root.iter('year') #扫描整个xml文档树,找到所有
for year in years:
    year.text=str(int(year.text)+1)
    year.set('updated','yes')
    year.set('version','1.0')
tree.write('a.xml')


#删除
for county in root.iter('country'):
    # print(county.tag)
    rank=county.find('rank')
    if int(rank.text) > 10:
        county.remove(rank)
tree.write('a.xml')

#增加节点
for county in root.iter('country'):
    e=ET.Element('egon')
    e.text='hello'
    e.attrib={'age':'18'}
    county.append(e)

tree.write('a.xml')
例子

二、面向对象

 1 面向过程的程序设计:核心是过程二字,过程指的是解决问题的步骤,即先干什么再干什么......面向过程的设计就好比精心设计好一条流水线,是一种机械式的思维方式。
 2 
 3 优点是:复杂度的问题流程化,进而简单化(一个复杂的问题,分成一个个小的步骤去实现,实现小的步骤将会非常简单)
 4 
 5 缺点是:一套流水线或者流程就是用来解决一个问题,生产汽水的流水线无法生产汽车,即便是能,也得是大改,改一个组件,牵一发而动全身。
 6 
 7 应用场景:一旦完成基本很少改变的场景,著名的例子有Linux內核,git,以及Apache HTTP Server等。
 8 
 9  
10 
11 面向对象的程序设计:核心是对象二字,(要理解对象为何物,必须把自己当成上帝,上帝眼里世间存在的万物皆为对象,不存在的也可以创造出来。面向对象的程序设计好比如来设计西游记,如来要解决的问题是把经书传给东土大唐,如来想了想解决这个问题需要四个人:唐僧,沙和尚,猪八戒,孙悟空,每个人都有各自的特征和技能(这就是对象的概念,特征和技能分别对应对象的数据属性和方法属性),然而这并不好玩,于是如来又安排了一群妖魔鬼怪,为了防止师徒四人在取经路上被搞死,又安排了一群神仙保驾护航,这些都是对象。然后取经开始,师徒四人与妖魔鬼怪神仙交互着直到最后取得真经。如来根本不会管师徒四人按照什么流程去取),对象是特征与技能的结合体,基于面向对象设计程序就好比在创造一个世界,你就是这个世界的上帝,存在的皆为对象,不存在的也可以创造出来,与面向过程机械式的思维方式形成鲜明对比,面向对象更加注重对现实世界的模拟,是一种“上帝式”的思维方式。
12 
13 优点是:解决了程序的扩展性。对某一个对象单独修改,会立刻反映到整个体系中,如对游戏中一个人物参数的特征和技能修改都很容易。
14 
15 缺点:
16 
17 1. 编程的复杂度远高于面向过程,不了解面向对象而立即上手基于它设计程序,极容易出现过度设计的问题。一些扩展性要求低的场景使用面向对象会徒增编程难度,比如管理linux系统的shell脚本就不适合用面向对象去设计,面向过程反而更加适合。
18 
19 2. 无法向面向过程的程序设计流水线式的可以很精准的预测问题的处理流程与结果,面向对象的程序一旦开始就由对象之间的交互解决问题,即便是上帝也无法准确地预测最终结果。于是我们经常看到对战类游戏,新增一个游戏人物,在对战的过程中极容易出现阴霸的技能,一刀砍死3个人,这种情况是无法准确预知的,只有对象之间交互才能准确地知道最终的结果。
20 
21 应用场景:需求经常变化的软件,一般需求的变化都集中在用户层,互联网应用,企业内部软件,游戏等都是面向对象的程序设计大显身手的好地方
22 
23 面向对象的程序设计并不是全部。对于一个软件质量来说,面向对象的程序设计只是用来解决扩展性。
什么是面向对象的程序设计及为什么要有它
 1 类即类别、种类,是面向对象设计最重要的概念,对象是特征与技能的结合体,而类则是一系列对象相似的特征与技能的结合体
 2 
 3 那么问题来了,先有的一个个具体存在的对象(比如一个具体存在的人),还是先有的人类这个概念,这个问题需要分两种情况去看
 4 
 5 在现实世界中:先有对象,再有类
 6 
 7 世界上肯定是先出现各种各样的实际存在的物体,然后随着人类文明的发展,人类站在不同的角度总结出了不同的种类,如人类、动物类、植物类等概念
 8 
 9 也就说,对象是具体的存在,而类仅仅只是一个概念,并不真实存在
10 
11 在程序中:务必保证先定义类,后产生对象
12 
13 这与函数的使用是类似的,先定义函数,后调用函数,类也是一样的,在程序中需要先定义类,后调用类
14 
15 不一样的是,调用函数会执行函数体代码返回的是函数体执行的结果,而调用类会产生对象,返回的是对象
16 
17  
18 
19 按照上述步骤,我们来定义一个类(我们站在老男孩学校的角度去看,在座的各位都是垃圾,sorry,都是学生)
类与对象
 在现实世界中:先有对象,再有类
 在程序中:先定义类,后产生对象
 类的特殊属性(了解即可)

属性查找

类有两种属性:数据属性和函数属性

1. 类的数据属性是所有对象共享的

2. 类的函数属性是绑定给对象用的

 View Code

 

1.继承

1.继承的基本形式

class ParentClass1(object): #定义父类
    pass

class ParentClass2: #定义父类
    pass

class SubClass1(ParentClass1): #单继承,基类是ParentClass1,派生类是SubClass
    pass

class SubClass2(ParentClass1,ParentClass2): #python支持多继承,用逗号分隔开多个继承的类
    pass
print(SubClass1.__bases__)
print(SubClass2.__bases__)
print(ParentClass1.__bases__)

  

 1 class OldboyPeople:
 2     school = 'oldboy'
 3     def __init__(self,name,age,sex):
 4         self.name=name
 5         self.age=age
 6         self.sex=sex
 7 
 8     def eat(self):
 9         print('is eating')
10 
11 class OldboyStudent(OldboyPeople):
12     def learn(self):
13         print('%s is learning'  %self.name)
14 
15 
16 class OldboyTeacher(OldboyPeople):
17     def __init__(self,name,age,sex,salary,title):
18         OldboyPeople.__init__(self,name,age,sex)
19         self.salary=salary
20         self.title=title
21 
22     def teach(self):
23         print('%s is teaching'  %self.name)
24 
25 
26 yl_obj=OldboyStudent('yanglei',28,'female')
27 egon_obj=OldboyTeacher('egon',18,'male',3.1,'沙河霸道金牌讲师')
28 
29 
30 # yl_obj.learn()
31 # yl_obj.eat()
32 
33 print(egon_obj.__dict__)
34 
35 '''
36 总结:
37 1 继承的功能之一:解决类与类之间的代码重复问题
38 2 继承是类与类之间的关系,是一种,什么是什么的关系
39 3 在子类派生出的新的属性,已自己的为准
40 4 在子类派生出的新的方法内重用父类的功能的方式:指名道姓法
41 OldboyPeople.__init__
42   这种调用方式本身与继承是没有关系
43 '''
例子与总结

2.继承实现原理

 1 #单继承
 2 class A:
 3     def f1(self):
 4         print('A.f1')
 5 
 6     def f2(self):
 7         print('A.f2')
 8         self.f1() #b.f1()
 9 
10 class B(A):
11     def f1(self):
12         print('B.f2')
13 
14 
15 b=B()
16 # b.f2=111111
17 b.f2()
18 
19 #多继承
20 class A:
21     def test(self):
22         print('A')
23 
24 class E:
25     def test(self):
26         print('E')
27 
28 class H:
29     def test(self):
30         print('H')
31 
32 class G(H):
33     def test(self):
34         print('G')
35 
36 class B(A):
37     def test(self):
38         print('B')
39 
40 class D(E):
41     def test(self):
42         print('D')
43 
44 class F(G):
45     def test(self):
46         print('F')
47 
48 class C(B,D,F):
49     def test(self):
50         print('C')
51 
52 
53 print(C.mro())
例子

3.子类方法重用父类功能super

 1 class OldboyPeople:
 2     school = 'oldboy'
 3     def __init__(self,name,age,sex):
 4         self.name=name
 5         self.age=age
 6         self.sex=sex
 7 
 8     def eat(self):
 9         print('is eating')
10     def teach(self):
11         print('这是父类的teach')
12 
13 class OldboyTeacher(OldboyPeople):
14     def __init__(self,name,age,sex,salary,title):
15         # OldboyPeople.__init__(self,name,age,sex)
16         #在Python2中需要写全:super(OldboyTeacher,self)
17         super().__init__(name,age,sex)
18         self.salary=salary
19         self.title=title
20 
21     def teach(self):
22         # OldboyPeople.teach(self)
23         super().teach()
24         print('%s is teaching'  %self.name)
25 print(OldboyTeacher.mro())
26 
27 egon_obj=OldboyTeacher('egon',18,'male',3.1,'沙河霸道金牌讲师')
28 # print(egon_obj.title)
29 # print(egon_obj.__dict__)
30 egon_obj.teach()
31 
32 
33 
34 
35 
36 
37 # 例子2:
38 class A:
39     def test(self):
40         super().test()
41 
42 class B:
43     def test(self):
44         print('B')
45 
46 class C(A,B):
47     pass
48 
49 # a=A()
50 # a.test()
51 
52 print(C.mro())
53 c=C()
54 c.test()
例子

4.组合

 1 class OldboyPeople:
 2     school = 'oldboy'
 3     def __init__(self,name,age,sex):
 4         self.name=name
 5         self.age=age
 6         self.sex=sex
 7 
 8     def eat(self):
 9         print('is eating')
10 
11 class OldboyStudent(OldboyPeople):
12 
13     def __init__(self,name,age,sex):
14         OldboyPeople.__init__(self,name,age,sex)
15         self.course=[]
16 
17     def learn(self):
18         print('%s is learning'  %self.name)
19 
20 
21 class OldboyTeacher(OldboyPeople):
22     def __init__(self,name,age,sex,salary,title):
23         OldboyPeople.__init__(self,name,age,sex)
24         self.salary=salary
25         self.title=title
26         self.course=[]
27 
28     def teach(self):
29         print('%s is teaching'  %self.name)
30 
31 
32 class Course:
33     def __init__(self,course_name,course_period,course_price):
34         self.course_name=course_name
35         self.course_period=course_period
36         self.course_price=course_price
37     def tell_info(self):
38         print('<课程名:%s 周期:%s 价格:%s>' %(self.course_name,self.course_period,self.course_price))
39 
40 python=Course('Python','6mons',3000)
41 linux=Course('Lnux','3mons',2000)
42 bigdata=Course('BigData','1mons',1000)
43 
44 # python.tell_info()
45 
46 
47 egon_obj=OldboyTeacher('egon',18,'male',3.1,'沙河霸道金牌讲师')
48 #
49 # egon_obj.course.append(python)
50 # egon_obj.course.append(linux)
51 #
52 # for obj in egon_obj.course:
53 #     obj.tell_info()
54 
55 
56 yl_obj=OldboyStudent('yanglei',28,'female')
57 yl_obj.course.append(python)
58 
59 for i in yl_obj.course:
60     # print(i.course_name,i.course_period,i.course_price)
61     i.tell_info()
例子
原文地址:https://www.cnblogs.com/ikere/p/7373948.html