python-學習 補充模塊;面向對象程序設計

1、模塊補充

  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

  更多詳細例子php

 [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 獲取全部節點html

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 獲取指定節點下全部的鍵值對python

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 獲取指定節點下全部的建linux

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的值git

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 檢查、刪除、設置指定組內的鍵值對shell

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 和 內容 進行進一步的處理而後再加密:app

 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模塊

建立子進程   詳細參考官網ide

 1 import subprocess
 2 
 3 # res=subprocess.Popen(r'dir D:\04-視頻錄製存放目錄\python18期\day7\xml模塊',
 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:\04-視頻錄製存放目錄\python18期\day7\xml模塊',
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')
例子

2、面向對象

 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()
例子
相關文章
相關標籤/搜索