Python 面向?qū)ο?/h3>
python是一門面向?qū)ο蟮恼Z言
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class myclass: # 創(chuàng)建類
num = 10 # 定義類的屬性(類的變量)
def __init__(self,name,age): # 構(gòu)造函數(shù) 在實(shí)例化該類的時(shí)候自動(dòng)調(diào)用該函數(shù)
self.name = name
self.age = age
def myfun(self):
return ('姓名:',self.name,'年齡:',self.age)
#創(chuàng)建類對(duì)象
newClass = myclass('mike','18')
#對(duì)象訪問類的屬性
print(newClass.name)
#對(duì)象訪問類的方法
print(newClass.myfun())
Python內(nèi)置類屬性
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class myclass: # 創(chuàng)建類
"""
這里是備注的文檔字符串
"""
num = 10 # 定義類的屬性(類的變量)
def __init__(self,name,age): # 構(gòu)造函數(shù) 在實(shí)例化該類的時(shí)候自動(dòng)調(diào)用該函數(shù)
self.name = name
self.age = age
def myfun(self):
return ('姓名:',self.name,'年齡:',self.age)
#創(chuàng)建類對(duì)象
newClass = myclass('mike','18')
print(newClass.__dict__) # 類的屬性(包含一個(gè)字典妥凳,由類的數(shù)據(jù)屬性組成) #OUTPUT {'name': 'mike', 'age': '18'}
print(newClass.__doc__) # 類的文檔字符串
# print(newClass.__name__) # python3的類沒有__name__這個(gè)屬性
print(newClass.__module__) # 類定義所在的模塊
# print(newClass.__bases__) # python3的類沒有__bases__這個(gè)屬性
python對(duì)象銷毀(垃圾回收)
引用計(jì)數(shù)器 :
- python 和java,php等語言一樣瓤狐,采用引用技術(shù)的技術(shù)來追蹤對(duì)象
- 在python內(nèi)部記錄著所有使用中的對(duì)象各有多少引用
- 一個(gè)內(nèi)部跟蹤變量昼牛,稱為一個(gè)引用計(jì)數(shù)器
- 當(dāng)對(duì)象被創(chuàng)建時(shí), 就創(chuàng)建了一個(gè)引用計(jì)數(shù), 當(dāng)這個(gè)對(duì)象不再需要時(shí)寡夹, 也就是說, 這個(gè)對(duì)象的引用計(jì)數(shù)變?yōu)? 時(shí)厂置, 它被垃圾回收菩掏。但是回收不是"立即"的, 由解釋器在適當(dāng)?shù)臅r(shí)機(jī)昵济,將垃圾對(duì)象占用的內(nèi)存空間回收
循環(huán)垃圾收集器:
- 循環(huán)引用指的是智绸,兩個(gè)對(duì)象相互引用,但是沒有其他變量引用他們
- python 的垃圾收集器實(shí)際上是一個(gè)引用計(jì)數(shù)器和一個(gè)循環(huán)垃圾收集器
- 作為引用計(jì)數(shù)的補(bǔ)充访忿, 垃圾收集器也會(huì)留心被分配的總量很大(及未通過引用計(jì)數(shù)銷毀的那些)的對(duì)象瞧栗。 在這種情況下, 解釋器會(huì)暫停下來海铆, 試圖清理所有未引用的循環(huán)
感覺循環(huán)垃圾收集器有點(diǎn)像時(shí)刻處于監(jiān)聽狀態(tài)
析構(gòu)函數(shù) del del在對(duì)象消逝的時(shí)候被調(diào)用迹恐,當(dāng)對(duì)象不再被使用時(shí),del方法運(yùn)行
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3))# 打印對(duì)象的id
del pt1
del pt2
del pt3
# OUTPUT 315754144 315754144 315754144 Point destroyed
類的繼承
類的繼承機(jī)制在面向?qū)ο缶幊踢^程中可以使代碼的共用型大大提高卧斟,提高了系統(tǒng)的可維護(hù)性
python繼承中的特點(diǎn):
- 在繼承中基類的構(gòu)造(init()方法)不會(huì)被自動(dòng)調(diào)用殴边,它需要在其派生類的構(gòu)造中親自專門調(diào)用
- 在調(diào)用基類的方法時(shí),需要加上基類的類名前綴珍语,且需要帶上self參數(shù)變量锤岸。區(qū)別于在類中調(diào)用普通函數(shù)時(shí)并不需要帶上self參數(shù)
- Python總是首先查找對(duì)應(yīng)類型的方法,如果它不能在派生類中找到對(duì)應(yīng)的方法板乙,它才開始到基類中逐個(gè)查找
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Parent: # 定義父類
parentInfo = '父類屬性168'
def __init__(self):
print('調(diào)用父類的構(gòu)造函數(shù)')
def parentMethod(self):
print('調(diào)用父類parentMethod方法')
def setParentInfo(self,info):
Parent.parentInfo = info
def getParentInfo(self):
return (Parent.parentInfo)
class Child(Parent): # 定義子類 繼承父類Parent
childInfo = '子類屬性168'
def __init__(self):
print('調(diào)用子類構(gòu)造函數(shù)')
# Parent.__init__(self) # 子類調(diào)用父類構(gòu)造函數(shù)需要加上self參數(shù)
def childMethod(self):
print('調(diào)用子類childMethod方法')
childClass = Child() # OUTPUT 調(diào)用子類構(gòu)造函數(shù) 當(dāng)實(shí)例化子類對(duì)象的時(shí)候 自動(dòng)調(diào)用子類的構(gòu)造函數(shù) 但是不會(huì)自動(dòng)調(diào)用父類的構(gòu)造函數(shù) 如果實(shí)例化子類的時(shí)候調(diào)用父類的構(gòu)造函數(shù) 需要 在子類構(gòu)造函數(shù)中調(diào)用一次父類的構(gòu)造函數(shù)
childClass.childMethod() # OUTPUT 調(diào)用子類childMethod方法
print(childClass.parentInfo) # OUTPUT 父類屬性168 Child子類繼承Parent父類 實(shí)例化Child子類對(duì)象可以訪問Parent父類的屬性
childClass.setParentInfo('訪問父類屬性')
print(childClass.getParentInfo()) # 訪問父類屬性 實(shí)例化子類對(duì)象 調(diào)用父類的getParentInfo方法
方法重寫
當(dāng)父類的方法無法滿足現(xiàn)有的業(yè)務(wù)需求的時(shí)候可以在子類重寫父類的方法
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Parent: # 定義父類
def myfun(self):
print('調(diào)用父類方法')
class Child(Parent):
def myfun(self):
print('子類重新父類myfun方法')
childClass = Child()
childClass.myfun() # OUTPUT 子類重新父類myfun方法
基礎(chǔ)重載方法
方法 | 描述 | 簡(jiǎn)單的調(diào)用 |
---|---|---|
init ( self [,args...] ) | 構(gòu)造函數(shù) | 簡(jiǎn)單的調(diào)用方法: obj = className(args) |
del( self ) | 析構(gòu)方法, 刪除一個(gè)對(duì)象 | 簡(jiǎn)單的調(diào)用方法 : dell obj |
repr( self ) | 轉(zhuǎn)化為供解釋器讀取的形式 | 簡(jiǎn)單的調(diào)用方法 : repr(obj) |
str( self ) | 用于將值轉(zhuǎn)化為適于人閱讀的形式 | 簡(jiǎn)單的調(diào)用方法 : str(obj) |
cmp ( self, x ) | 對(duì)象比較 | 簡(jiǎn)單的調(diào)用方法 : cmp(obj, x) |
add | 運(yùn)算符重載算法+ | 簡(jiǎn)單的調(diào)用方法 : add(obj, x) |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2, 10)
print(v1) #OUTPUT Vector (2, 10)
v2 = Vector(5, -2)
print(v2) #OUTPUT Vector (5, -2)
print(v1 + v2) #OUTPUT Vector (7, 8)
python類的私有屬性與私有方法
類的私有屬性
- __private_attrs:兩個(gè)下劃線開頭是偷,聲明該屬性為私有,不能在類地外部被使用或直接訪問募逞。在類內(nèi)部的方法中使用時(shí) self.__private_attrs
類的使用方法
- __private_method:兩個(gè)下劃線開頭蛋铆,聲明該方法為私有方法,不能在類地外部調(diào)用放接。在類的內(nèi)部調(diào)用 self.__private_methods
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Test:
publicInfo = 10
__privateInfo = 20
def getPrivateInfo(self):
print(self.__privateInfo)
def publicFun(self):
print('調(diào)用公共方法')
def __privateFun(self):
print('調(diào)用私有方法')
testClass = Test()
print(testClass.publicInfo) # OUTPUT 10 訪問共用屬性
# print(testClass.__privateInfo) # 會(huì)報(bào)錯(cuò) 類的外部 實(shí)例化該類的對(duì)象不能訪問類的私有屬性
print(testClass.getPrivateInfo()) # 20 如果 在外部實(shí)例化類對(duì)象 想訪問類的私有屬性 需要通過訪問 類的公共對(duì)象 通過類內(nèi)部的公共方法 通過該方法來間接訪問類的私有屬性
# print(testClass.__privateFun()) # 會(huì)報(bào)錯(cuò) 類的外部 實(shí)例化該類的對(duì)象不能訪問類的私有方法 得借助類內(nèi)部的公共方法來間接訪問
Python正則表達(dá)式
- 正則表達(dá)式是一個(gè)特殊的字符序列刺啦,它能幫助你方便的檢查一個(gè)字符串是否與某種模式匹配
- re 模塊使 Python 語言擁有全部的正則表達(dá)式功能
- compile 函數(shù)根據(jù)一個(gè)模式字符串和可選的標(biāo)志參數(shù)生成一個(gè)正則表達(dá)式對(duì)象。該對(duì)象擁有一系列方法用于正則表達(dá)式匹配和替換
- re 模塊也提供了與這些方法功能完全一致的函數(shù)透乾,這些函數(shù)使用一個(gè)模式字符串做為它們的第一個(gè)參數(shù)
re.match函數(shù)
re.match 嘗試從字符串的開始匹配一個(gè)模式 匹配成功re.match方法返回一個(gè)匹配的對(duì)象洪燥,否則返回None
函數(shù)語法:re.match(pattern, string, flags=0)
參數(shù) | 描述 |
---|---|
pattern | 匹配的正則表達(dá)式 |
string | 要匹配的字符串 |
flags | 標(biāo)志位磕秤,用于控制正則表達(dá)式的匹配方式,如:是否區(qū)分大小寫捧韵,多行匹配等等 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
pattern = '^[1-9]{2,3}[a-z]$'
string = '19a'
res = re.match(pattern,string,flags=0)
print(res) # OUTPUT <_sre.SRE_Match object; span=(0, 1), match='1'> 匹配成功返回一個(gè)對(duì)象 反之返回none
re.search方法
re.search 會(huì)在字符串內(nèi)查找模式匹配市咆,直到找到第一個(gè)匹配
函數(shù)語法:re.search(pattern, string, flags=0)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
pattern = '^[1-9]{2,3}[a-z]$'
string = '19a'
data = re.search(pattern,string,flags=0)
print(data) # OUTPUT <_sre.SRE_Match object; span=(0, 1), match='1'> 匹配成功返回一個(gè)對(duì)象 反之返回none
獲取匹配表達(dá)式 group(num) 或 groups()
匹配對(duì)象方法 | 描述 |
---|---|
group(num=0) | 匹配的整個(gè)表達(dá)式的字符串,group() 可以一次輸入多個(gè)組號(hào)再来,在這種情況下它將返回一個(gè)包含那些組所對(duì)應(yīng)值的元組 |
groups() | 返回一個(gè)包含所有小組字符串的元組蒙兰,從 1 到 所含的小組號(hào) |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
pattern = '[1-9]{2,3}[a-z]'
string = '19a88b9999a69n'
res = re.search(pattern,string,flags=0)
if(res):
print(res.group())
else:
print('no matches')
re.match與re.search的區(qū)別
re.match只匹配字符串的開始,如果字符串開始不符合正則表達(dá)式芒篷,則匹配失敗搜变,函數(shù)返回None;而re.search匹配整個(gè)字符串针炉,直到找到一個(gè)匹配
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print("match --> matchObj.group() : ", matchObj.group())
else:
print("No match!!")
matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
print("search --> matchObj.group() : ", matchObj.group())
else:
print("No match!!")
re.sub方法
檢索與替換函數(shù)
函數(shù)語法:re.sub(pattern, repl, string, max=0)
返回的字符串是在字符串中用 RE 最左邊不重復(fù)的匹配來替換挠他。如果模式?jīng)]有發(fā)現(xiàn),字符將被沒有改變地返回
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
pattern = r'\D'
phone = '10086-10086-10086'
print(re.sub(pattern,'',phone)) # OUTPUT 100861008610086
正則表達(dá)式修飾符 - 可選標(biāo)志
修飾符 | 描述 |
---|---|
re.I | 使匹配對(duì)大小寫不敏感 |
re.L | 做本地化識(shí)別(locale-aware)匹配 |
re.M | 多行匹配篡帕,影響 ^ 和 $ |
re.S | 使 . 匹配包括換行在內(nèi)的所有字符 |
re.U | 根據(jù)Unicode字符集解析字符殖侵。這個(gè)標(biāo)志影響 \w, \W, \b, \B. |
re.X | 該標(biāo)志通過給予你更靈活的格式以便你將正則表達(dá)式寫得更易于理解 |
正則表達(dá)式模式
正則表達(dá)式模式語法中的特殊元素
模式 | 描述 | |
---|---|---|
^ | 匹配字符串的開頭 | |
$ | 匹配字符串的末尾 | |
. | 匹配任意字符,除了換行符镰烧,當(dāng)re.DOTALL標(biāo)記被指定時(shí)拢军,則可以匹配包括換行符的任意字符 | |
[...] | 用來表示一組字符,單獨(dú)列出:[amk] 匹配 'a','m'或'k' | |
[^...] | 不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符 | |
re* | 匹配0個(gè)或多個(gè)的表達(dá)式 | |
re+ | 匹配1個(gè)或多個(gè)的表達(dá)式 | |
re? | 匹配0個(gè)或1個(gè)由前面的正則表達(dá)式定義的片段怔鳖,非貪婪方式 | |
re{ n} | 匹配n個(gè) | |
re{ n,} | 匹配n或者n個(gè)以上 | |
re{ n, m} | 匹配 n 到 m 次由前面的正則表達(dá)式定義的片段茉唉,貪婪方式 | |
a | b | 匹配a或b |
(re) | G匹配括號(hào)內(nèi)的表達(dá)式,也表示一個(gè)組 | |
(?imx) | 正則表達(dá)式包含三種可選標(biāo)志:i, m, 或 x 结执。只影響括號(hào)中的區(qū)域 | |
(?-imx) | 正則表達(dá)式關(guān)閉 i, m, 或 x 可選標(biāo)志度陆。只影響括號(hào)中的區(qū)域 | |
(?: re) | 類似 (...), 但是不表示一個(gè)組 | |
(?imx: re) | 在括號(hào)中使用i, m, 或 x 可選標(biāo)志 | |
(?-imx: re) | 在括號(hào)中不使用i, m, 或 x 可選標(biāo)志 | |
(?#...) | 注釋 | |
(?= re) | 前向肯定界定符。如果所含正則表達(dá)式昌犹,以 ... 表示坚芜,在當(dāng)前位置成功匹配時(shí)成功,否則失敗斜姥。但一旦所含表達(dá)式已經(jīng)嘗試,匹配引擎根本沒有提高沧竟;模式的剩余部分還要嘗試界定符的右邊 | |
(?! re) | 前向否定界定符铸敏。與肯定界定符相反;當(dāng)所含表達(dá)式不能在字符串當(dāng)前位置匹配時(shí)成功 | |
(?> re) | 匹配的獨(dú)立模式悟泵,省去回溯 | |
\w | 匹配字母數(shù)字 | |
\W | 匹配非字母數(shù)字 | |
\s | 匹配任意空白字符杈笔,等價(jià)于 [\t\n\r\f] | |
\S | 匹配任意非空字符 | |
\d | 匹配任意數(shù)字,等價(jià)于 [0-9] | |
\D | 匹配任意非數(shù)字 | |
\A | 匹配字符串開始 | |
\Z | 匹配字符串結(jié)束糕非,如果是存在換行蒙具,只匹配到換行前的結(jié)束字符串 | |
\z | 匹配字符串結(jié)束 | |
\G | 匹配最后匹配完成的位置 | |
\b | 匹配一個(gè)單詞邊界球榆,也就是指單詞和空格間的位置。例如禁筏, 'er\b' 可以匹配"never" 中的 'er'持钉,但不能匹配 "verb" 中的 'er' | |
\B | 匹配非單詞邊界。'er\B' 能匹配 "verb" 中的 'er'篱昔,但不能匹配 "never" 中的 'er' | |
\n, \t, 等 | 匹配一個(gè)換行符每强。匹配一個(gè)制表符。等 | |
\1...\9 | 匹配第n個(gè)分組的子表達(dá)式 | |
\10 | 匹配第n個(gè)分組的子表達(dá)式州刽,如果它經(jīng)匹配空执。否則指的是八進(jìn)制字符碼的表達(dá)式 |
python正則匹配電話號(hào)碼 郵箱
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
# 移動(dòng)號(hào)段:134、135穗椅、136辨绊、137、138匹表、139邢羔、150、151桑孩、152拜鹤、157、158流椒、159敏簿、187、188宣虾、147(數(shù)據(jù)卡)
# 聯(lián)通號(hào)段: 130惯裕、131、132绣硝、155蜻势、156、185鹉胖、186
# 電信號(hào)段:133握玛、180、189
#匹配電話號(hào)碼
def match_phone_num(phone):
pattern = '^1(3[0-9]|5[0-9]|8[0-9]|1[4])\d{8}$'
res = re.match(pattern,phone,flags=0)
if(res):
return(1)
else:
return(0)
# 匹配郵箱
def match_email(email):
pattern = "^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$"
res = re.match(pattern,email,flags=0)
if(res):
return(1)
else:
return(0)
phone = '15013884809'
print(match_phone_num(phone))
email = '301858962@qq.com'
print(match_email(email))
Python使用SMTP發(fā)送郵件
- SMTP(Simple Mail Transfer Protocol)即簡(jiǎn)單郵件傳輸協(xié)議,它是一組用于由源地址到目的地址傳送郵件的規(guī)則甫菠,由它來控制信件的中轉(zhuǎn)方式
- python的smtplib提供了一種很方便的途徑發(fā)送電子郵件挠铲。它對(duì)smtp協(xié)議進(jìn)行了簡(jiǎn)單的封裝
創(chuàng)建stmp對(duì)象語法:smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
參數(shù)說明:
- host: SMTP 服務(wù)器主機(jī)。 你可以指定主機(jī)的ip地址或者域名如:w3cschool.cn寂诱,這個(gè)是可選參數(shù)
- port: 如果你提供了 host 參數(shù), 你需要指定 SMTP 服務(wù)使用的端口號(hào)拂苹,一般情況下SMTP端口號(hào)為25
- local_hostname: 如果SMTP在你的本機(jī)上,你只需要指定服務(wù)器地址為 localhost 即可
sendmail方法
語法:SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
參數(shù)說明:
- from_addr: 郵件發(fā)送者地址
- to_addrs: 字符串列表痰洒,郵件發(fā)送地址
- msg: 發(fā)送消息
使用Python發(fā)送HTML格式的郵件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
def sendEmail(to_list,sub,content,send_name):
#定義郵箱配置信息 暫時(shí)沒有用到類常量
mail_host = "smtp.qq.com" # 設(shè)置服務(wù)器
mail_user = "168168168@qq.com" # 用戶名
mail_pass = "ojvabcreejiuddhf" # 口令
mail_postfix = "qq.com" # 發(fā)件箱的后綴
#發(fā)件人格式 發(fā)送標(biāo)題 發(fā)送郵件內(nèi)容格式 字符集信息設(shè)置
me = send_name + "<" + mail_user + "@" + mail_postfix + ">" # 這里的hello可以任意設(shè)置瓢棒,收到信后浴韭,將按照設(shè)置顯示
msg = MIMEText(content, _subtype='html', _charset='gb2312') # 創(chuàng)建一個(gè)實(shí)例,這里設(shè)置為html格式郵件
msg['Subject'] = sub # 設(shè)置主題
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP() # 創(chuàng)建 stmp對(duì)象
s.connect(host=mail_host, port=25,source_address=None) # 連接smtp服務(wù)器 # def connect(self, host='localhost', port=0, source_address=None):
s.starttls()
s.login(mail_user, mail_pass) # 登陸服務(wù)器
res = s.sendmail(mail_user, to_list,msg.as_string()) # def sendmail(self, from_addr, to_addrs, msg, mail_options=[],rcpt_options=[])
except:
print('發(fā)送失敗')
else:
print('發(fā)送成功')
# 調(diào)用發(fā)送郵件方法
to_list = ['1698562426@qq.com']
sub = '網(wǎng)上購票系統(tǒng)--用戶支付通知'
content = "<a target='_blank'>點(diǎn)擊查看詳情</a>"
send_name = 'mike'
sendEmail(to_list,sub,content,send_name)
發(fā)送帶附件郵件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def sendEmail(to_list,sub,content,send_name,attchment = []):
"""
發(fā)送郵件方法
:param to_list: list 收件人列表
:param sub: string 主體
:param content: string 內(nèi)容
:param send_name: string 發(fā)送人名字
:param attchment: list 附件[['附件地址','附件名稱(含后綴)'],]
:return: int 成功 1 失敗 0
"""
#定義郵箱配置信息 暫時(shí)沒有用到類常量
mail_host = "smtp.qq.com" # 設(shè)置服務(wù)器
mail_user = "3169464903@qq.com" # 用戶名
mail_pass = "ojvekihaejiuddhf" # 口令
mail_postfix = "qq.com" # 發(fā)件箱的后綴
#發(fā)件人格式 發(fā)送標(biāo)題 發(fā)送郵件內(nèi)容格式 字符集信息設(shè)置
me = send_name + "<" + mail_user + ">" # 這里的hello可以任意設(shè)置脯宿,收到信后念颈,將按照設(shè)置顯示
msg = MIMEMultipart() # 創(chuàng)建MIMEMultipart對(duì)象
htmltext = MIMEText(content, _subtype='html', _charset='gb2312') # 創(chuàng)建一個(gè)實(shí)例,這里設(shè)置為html格式郵件
msg.attach(htmltext) # 將html正文文本添加到msg
msg['Subject'] = sub # 設(shè)置主題
msg['From'] = me # 設(shè)置發(fā)件人格式
msg['To'] = ";".join(to_list) # 設(shè)置收件人list表
# 含附件的情況
if(len(attchment)):
for val in attchment: #構(gòu)造附件
att = MIMEText(open(val[0], 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename= ' + val[1]#這里的filename可以任意寫嗅绰,寫什么名字舍肠,郵件中顯示什么名字
msg.attach(att)
else:
pass
try:
s = smtplib.SMTP() # 創(chuàng)建 stmp對(duì)象
s.connect(host=mail_host, port=25,source_address=None) # 連接smtp服務(wù)器 # def connect(self, host='localhost', port=0, source_address=None):
s.starttls()
s.login(mail_user, mail_pass) # 登陸服務(wù)器
res = s.sendmail(mail_user, to_list,msg.as_string()) # def sendmail(self, from_addr, to_addrs, msg, mail_options=[],rcpt_options=[])
except:
print('發(fā)送失敗')
return (0)
else:
print('發(fā)送成功')
return (1)
# 調(diào)用發(fā)送郵件方法
to_list = ['1536592426@qq.com']
sub = '網(wǎng)上購票系統(tǒng)--用戶支付通知'
content = "<a target='_blank'>點(diǎn)擊查看詳情</a>"
send_name = 'mike'
attchment = [['E:\\demo.jpg','123.jpg'],] # 二維列表 [['文件地址','文件名稱(含后綴)']]
sendEmail(to_list,sub,content,send_name,attchment)
Python 網(wǎng)絡(luò)編程
Python 提供了兩個(gè)級(jí)別訪問的網(wǎng)絡(luò)服務(wù):
- 低級(jí)別的網(wǎng)絡(luò)服務(wù)支持基本的 Socket,它提供了標(biāo)準(zhǔn)的 BSD Sockets API,可以訪問底層操作系統(tǒng)Socket接口的全部方法
- 高級(jí)別的網(wǎng)絡(luò)服務(wù)模塊 SocketServer, 它提供了服務(wù)器中心類韵卤,可以簡(jiǎn)化網(wǎng)絡(luò)服務(wù)器的開發(fā)
Socket又稱"套接字",應(yīng)用程序通常通過"套接字"向網(wǎng)絡(luò)發(fā)出請(qǐng)求或者應(yīng)答網(wǎng)絡(luò)請(qǐng)求肌括,使主機(jī)間或者一臺(tái)計(jì)算機(jī)上的進(jìn)程間可以通訊
socket()函數(shù):
Python 中,我們用 socket()函數(shù)來創(chuàng)建套接字
語法:socket.socket([family[, type[, proto]]])
參數(shù):
- family: 套接字家族可以使AF_UNIX或者AF_INET
- type: 套接字類型可以根據(jù)是面向連接的還是非連接分為SOCK_STREAM或SOCK_DGRAM
- protocol: 一般不填默認(rèn)為0
Socket 對(duì)象(內(nèi)建)方法
函數(shù) | 描述 |
---|---|
服務(wù)器端套接字 | |
s.bind() | 綁定地址(host,port)到套接字酣难, 在AF_INET下,以元組(host,port)的形式表示地址 |
s.listen() | 開始TCP監(jiān)聽谍夭。backlog指定在拒絕連接之前,操作系統(tǒng)可以掛起的最大連接數(shù)量憨募。該值至少為1紧索,大部分應(yīng)用程序設(shè)為5就可以了 |
s.accept() | 被動(dòng)接受TCP客戶端連接,(阻塞式)等待連接的到來 |
客戶端套接字 | |
s.connect() | 主動(dòng)初始化TCP服務(wù)器連接,菜谣。一般address的格式為元組(hostname,port)珠漂,如果連接出錯(cuò),返回socket.error錯(cuò)誤 |
s.connect_ex() | connect()函數(shù)的擴(kuò)展版本,出錯(cuò)時(shí)返回出錯(cuò)碼,而不是拋出異常 |
公共用途的套接字函數(shù) | |
s.recv() | 接收TCP數(shù)據(jù)尾膊,數(shù)據(jù)以字符串形式返回媳危,bufsize指定要接收的最大數(shù)據(jù)量。flag提供有關(guān)消息的其他信息冈敛,通炒Γ可以忽略 |
s.send() | 發(fā)送TCP數(shù)據(jù),將string中的數(shù)據(jù)發(fā)送到連接的套接字抓谴。返回值是要發(fā)送的字節(jié)數(shù)量暮蹂,該數(shù)量可能小于string的字節(jié)大小 |
s.sendall() | 完整發(fā)送TCP數(shù)據(jù),完整發(fā)送TCP數(shù)據(jù)齐邦。將string中的數(shù)據(jù)發(fā)送到連接的套接字椎侠,但在返回之前會(huì)嘗試發(fā)送所有數(shù)據(jù)。成功返回None措拇,失敗則拋出異常 |
s.recvform() | 接收UDP數(shù)據(jù),與recv()類似慎宾,但返回值是(data,address)丐吓。其中data是包含接收數(shù)據(jù)的字符串浅悉,address是發(fā)送數(shù)據(jù)的套接字地址 |
s.sendto() | 發(fā)送UDP數(shù)據(jù),將數(shù)據(jù)發(fā)送到套接字券犁,address是形式為(ipaddr术健,port)的元組,指定遠(yuǎn)程地址粘衬。返回值是發(fā)送的字節(jié)數(shù) |
s.close() | 關(guān)閉套接字 |
s.getpeername() | 返回連接套接字的遠(yuǎn)程地址荞估。返回值通常是元組(ipaddr,port) |
s.getsockname() | 返回套接字自己的地址。通常是一個(gè)元組(ipaddr,port) |
s.setsockopt(level,optname,value) | 設(shè)置給定套接字選項(xiàng)的值 |
s.getsockopt(level,optname[.buflen]) | 返回套接字選項(xiàng)的值 |
s.settimeout(timeout) | 設(shè)置套接字操作的超時(shí)期稚新,timeout是一個(gè)浮點(diǎn)數(shù)勘伺,單位是秒。值為None表示沒有超時(shí)期褂删。一般飞醉,超時(shí)期應(yīng)該在剛創(chuàng)建套接字時(shí)設(shè)置,因?yàn)樗鼈兛赡苡糜谶B接的操作(如connect()) |
s.gettimeout() | 返回當(dāng)前超時(shí)期的值屯阀,單位是秒缅帘,如果沒有設(shè)置超時(shí)期,則返回None |
s.fileno() | 返回套接字的文件描述符 |
s.setblocking(flag) | 如果flag為0难衰,則將套接字設(shè)為非阻塞模式钦无,否則將套接字設(shè)為阻塞模式(默認(rèn)值)。非阻塞模式下盖袭,如果調(diào)用recv()沒有發(fā)現(xiàn)任何數(shù)據(jù)失暂,或send()調(diào)用無法立即發(fā)送數(shù)據(jù),那么將引起socket.error異常 |
s.makefile() | 創(chuàng)建一個(gè)與該套接字相關(guān)連的文件 |
服務(wù)端
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import socket # 導(dǎo)入 socket 模塊
s = socket.socket() # 創(chuàng)建 socket 對(duì)象
host = socket.gethostname() # 獲取本地主機(jī)名
port = 12309 # 設(shè)置端口
s.bind((host, port)) # 綁定端口
s.listen(5) # 等待客戶端連接
while True:
c, addr = s.accept() # 建立客戶端連接苍凛。
print('連接地址:', addr)
c.send('大數(shù)據(jù)的前景還可以趣席,加油,騷年4己P恰!'.encode())
c.close() # 關(guān)閉連接
客戶端
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import socket # 導(dǎo)入 socket 模塊
s = socket.socket() # 創(chuàng)建 socket 對(duì)象
host = socket.gethostname() # 獲取本地主機(jī)名
port = 12309 # 設(shè)置端口好
s.connect((host, port))
print(s.recv(1024).decode())
s.close()
Python Internet 模塊
協(xié)議 | 功能用處 | 端口號(hào) | Python 模塊 |
---|---|---|---|
HTTP | 網(wǎng)頁訪問 | 80 | httplib, urllib, xmlrpclib |
NNTP | 閱讀和張貼新聞文章悠栓,俗稱為"帖子" | 119 | nntplib |
FTP | 文件傳輸 | 20 | ftplib, urllib |
SMTP | 發(fā)送郵件 | 25 | smtplib |
POP3 | 接收郵件 | 110 | poplib |
IMAP4 | 獲取郵件 | 143 | imaplib |
Telnet | 命令行 | 23 | telnetlib |
Gopher | 信息查找 | 70 | gopherlib, urllib |
Python 多線程
多線程類似于同時(shí)執(zhí)行多個(gè)不同程序霉涨,多線程運(yùn)行有如下優(yōu)點(diǎn):
- 使用線程可以把占據(jù)長(zhǎng)時(shí)間的程序中的任務(wù)放到后臺(tái)去處理
- 用戶界面可以更加吸引人,這樣比如用戶點(diǎn)擊了一個(gè)按鈕去觸發(fā)某些事件的處理惭适,可以彈出一個(gè)進(jìn)度條來顯示處理的進(jìn)度
- 程序的運(yùn)行速度可能加快
- 在一些等待的任務(wù)實(shí)現(xiàn)上如用戶輸入笙瑟、文件讀寫和網(wǎng)絡(luò)收發(fā)數(shù)據(jù)等,線程就比較有用了癞志。在這種情況下我們可以釋放一些珍貴的資源如內(nèi)存占用等等
線程在執(zhí)行過程中與進(jìn)程還是有區(qū)別的往枷。每個(gè)獨(dú)立的線程有一個(gè)程序運(yùn)行的入口、順序執(zhí)行序列和程序的出口。但是線程不能夠獨(dú)立執(zhí)行错洁,必須依存在應(yīng)用程序中秉宿,由應(yīng)用程序提供多個(gè)線程執(zhí)行控制
每個(gè)線程都有他自己的一組CPU寄存器,稱為線程的上下文屯碴,該上下文反映了線程上次運(yùn)行該線程的CPU寄存器的狀態(tài)描睦。
指令指針和堆棧指針寄存器是線程上下文中兩個(gè)最重要的寄存器,線程總是在進(jìn)程得到上下文中運(yùn)行的忱叭,這些地址都用于標(biāo)志擁有線程的進(jìn)程地址空間中的內(nèi)存
- 線程可以被搶占(中斷)
- 在其他線程正在運(yùn)行時(shí)埂息,線程可以暫時(shí)擱置(也稱為睡眠) -- 這就是線程的退讓
什么是進(jìn)程:
進(jìn)程是指在操作系統(tǒng)中正在運(yùn)行的一個(gè)應(yīng)用程序铲掐,線程是指進(jìn)程內(nèi)獨(dú)立執(zhí)行某個(gè)任務(wù)的一個(gè)單元
Python中使用線程的兩種方式:函數(shù)或者用類來包裝線程對(duì)象
函數(shù)式:調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新線程
語法:thread.start_new_thread ( function, args[, kwargs] )
參數(shù)說明:
- function - 線程函數(shù)
- args - 傳遞給線程函數(shù)的參數(shù),他必須是個(gè)tuple類型
- kwargs - 可選參數(shù)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import _thread # python3 改成用_thread模塊使用進(jìn)程,thread已丟棄使用
import time
# 為線程定義一個(gè)函數(shù)
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % ( threadName, time.ctime(time.time()) ))
# 創(chuàng)建兩個(gè)線程
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print("Error: unable to start thread")
while 1: # 定義一個(gè)無限循環(huán)避免腳本執(zhí)行結(jié)束
pass
線程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束搭盾;也可以在線程函數(shù)中調(diào)用thread.exit()蝌以,他拋出SystemExit exception溶推,達(dá)到退出線程的目的
線程模塊
Python通過兩個(gè)標(biāo)準(zhǔn)庫thread和threading提供對(duì)線程的支持舰褪。thread提供了低級(jí)別的晃酒、原始的線程以及一個(gè)簡(jiǎn)單的鎖。threadding相當(dāng)于是thread的升級(jí)版,python3中丟棄了thread用_thread替代
thread 模塊提供的其他方法:
- threading.currentThread(): 返回當(dāng)前的線程變量
- threading.enumerate(): 返回一個(gè)包含正在運(yùn)行的線程的list。正在運(yùn)行指線程啟動(dòng)后爵政、結(jié)束前等龙,不包括啟動(dòng)前和終止后的線程
- threading.activeCount(): 返回正在運(yùn)行的線程數(shù)量泥畅,與len(threading.enumerate())有相同的結(jié)果
除了使用方法外,線程模塊同樣提供了Thread類來處理線程有决,Thread類提供了以下方法:
- run(): 用以表示線程活動(dòng)的方法
- start():啟動(dòng)線程活動(dòng)
- join([time]): 等待至線程中止台汇。這阻塞調(diào)用線程直至線程的join() 方法被調(diào)用中止-正常退出或者拋出未處理的異常-或者是可選的超時(shí)發(fā)生
- isAlive(): 返回線程是否活動(dòng)的
- getName(): 返回線程名
- setName(): 設(shè)置線程名
使用Threading模塊創(chuàng)建線程
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import _thread
import time
exitFlag = 0
class myThread (threading.Thread): #繼承父類threading.Thread
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self): #把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會(huì)直接運(yùn)行run函數(shù)
print("Starting " + self.name)
print_time(self.name, self.counter, 5)
print("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
_thread.exit()
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# 創(chuàng)建新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 開啟線程
thread1.start()
thread2.start()
print("Exiting Main Thread")
線程同步
如果多個(gè)線程共同對(duì)某個(gè)數(shù)據(jù)修改瞳步,則可能出現(xiàn)不可預(yù)料的結(jié)果,為了保證數(shù)據(jù)的正確性劣坊,需要對(duì)多個(gè)線程進(jìn)行同步嘀倒。
使用Thread對(duì)象的Lock和Rlock可以實(shí)現(xiàn)簡(jiǎn)單的線程同步,這兩個(gè)對(duì)象都有acquire方法和release方法局冰,對(duì)于那些需要每次只允許一個(gè)線程操作的數(shù)據(jù)测蘑,可以將其操作放到acquire和release方法之間。如下:
多線程的優(yōu)勢(shì)在于可以同時(shí)運(yùn)行多個(gè)任務(wù)(至少感覺起來是這樣)康二。但是當(dāng)線程需要共享數(shù)據(jù)時(shí)碳胳,可能存在數(shù)據(jù)不同步的問題。
考慮這樣一種情況:一個(gè)列表里所有元素都是0沫勿,線程"set"從后向前把所有元素改成1挨约,而線程"print"負(fù)責(zé)從前往后讀取列表并打印味混。
那么,可能線程"set"開始改的時(shí)候诫惭,線程"print"便來打印列表了翁锡,輸出就成了一半0一半1,這就是數(shù)據(jù)的不同步夕土。為了避免這種情況馆衔,引入了鎖的概念。
鎖有兩種狀態(tài)——鎖定和未鎖定隘弊。每當(dāng)一個(gè)線程比如"set"要訪問共享數(shù)據(jù)時(shí)哈踱,必須先獲得鎖定;如果已經(jīng)有別的線程比如"print"獲得鎖定了梨熙,那么就讓線程"set"暫停,也就是同步阻塞刀诬;等到線程"print"訪問完畢咽扇,釋放鎖以后,再讓線程"set"繼續(xù)陕壹。
經(jīng)過這樣的處理质欲,打印列表時(shí)要么全部輸出0,要么全部輸出1糠馆,不會(huì)再出現(xiàn)一半0一半1的尷尬場(chǎng)面
感覺有點(diǎn)像是mysql的鎖機(jī)制
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self) # 繼承的thread構(gòu)造函數(shù)不會(huì)指定允許,需要在當(dāng)前構(gòu)造函數(shù)調(diào)用一次
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting " + self.name)
# 獲得鎖嘶伟,成功獲得鎖定后返回True
# 可選的timeout參數(shù)不填時(shí)將一直阻塞直到獲得鎖定
# 否則超時(shí)后將返回False
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 釋放鎖
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# 創(chuàng)建新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 開啟新線程
thread1.start()
thread2.start()
# 添加線程到線程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有線程完成
for t in threads:
t.join()
print("Exiting Main Thread")
線程優(yōu)先級(jí)隊(duì)列( Queue)
Python的Queue模塊中提供了同步的、線程安全的隊(duì)列類又碌,包括FIFO(先入先出)隊(duì)列Queue九昧,LIFO(后入先出)隊(duì)列LifoQueue,和優(yōu)先級(jí)隊(duì)列PriorityQueue毕匀。這些隊(duì)列都實(shí)現(xiàn)了鎖原語铸鹰,能夠在多線程中直接使用≡聿恚可以使用隊(duì)列來實(shí)現(xiàn)線程間的同步
Queue模塊中的常用方法:
- Queue.qsize() 返回隊(duì)列的大小
- Queue.empty() 如果隊(duì)列為空蹋笼,返回True,反之False
- Queue.full() 如果隊(duì)列滿了,返回True,反之False
- Queue.full 與 maxsize 大小對(duì)應(yīng)
- Queue.get([block[, timeout]])獲取隊(duì)列躁垛,timeout等待時(shí)間
- Queue.get_nowait() 相當(dāng)Queue.get(False)
- Queue.put(item) 寫入隊(duì)列剖毯,timeout等待時(shí)間
- Queue.put_nowait(item) 相當(dāng)Queue.put(item, False)
- Queue.task_done() 在完成一項(xiàng)工作之后,Queue.task_done()函數(shù)向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個(gè)信號(hào)
- Queue.join() 實(shí)際上意味著等到隊(duì)列為空教馆,再執(zhí)行別的操作
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from queue import Queue # 引入Queue隊(duì)列模塊
import threading # 引入線程模塊
import time # 引入時(shí)間模塊
exitFlag = 0 # 初始化屬性
class myThread (threading.Thread): # 定義類 繼承線程模塊類
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self): # 把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會(huì)直接運(yùn)行run函數(shù)
print("Starting " + self.name)
process_data(self.name, self.q)
print("Exiting " + self.name)
def process_data(threadName, q):
while not exitFlag: # 只要 exitFlag不為0循環(huán)將繼承
queueLock.acquire() # 獲得鎖逊谋,成功獲得鎖定后返回True
if not workQueue.empty(): # 隊(duì)列不為空情況下執(zhí)行下面操作
data = q.get() # 獲取隊(duì)列
# print(data)
# exit()
queueLock.release() # 釋放鎖
print("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock() # 創(chuàng)建鎖對(duì)象
workQueue = Queue(10) # 創(chuàng)建隊(duì)列對(duì)象設(shè)定隊(duì)列最大大小
threads = [] # 數(shù)據(jù)初始化
threadID = 1 # 數(shù)據(jù)初始化
# 創(chuàng)建新線程
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# 填充隊(duì)列
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# 等待隊(duì)列清空
while not workQueue.empty():
pass
# 通知線程是時(shí)候退出
exitFlag = 1
# 等待所有線程完成
for t in threads:
t.join()
print("Exiting Main Thread")
什么是協(xié)成:
簡(jiǎn)單點(diǎn)說協(xié)程是進(jìn)程和線程的升級(jí)版,進(jìn)程和線程都面臨著內(nèi)核態(tài)和用戶態(tài)的切換問題而耗費(fèi)許多切換時(shí)間活玲,而協(xié)程就是用戶自己控制切換的時(shí)機(jī)涣狗,不需要再陷入系統(tǒng)的內(nèi)核態(tài)
GIL線程全局鎖:
線程全局鎖(Global Interperter Lock),即Python為了保證線程安全而采用的獨(dú)立線程運(yùn)行的限制谍婉,說白了就是一個(gè)核只能在同一時(shí)刻運(yùn)行一個(gè)線程。
解決辦法就是多進(jìn)程和協(xié)程(協(xié)程也只是單CPU,但是能減小切換代價(jià)提升性能)镀钓。
Python JSON
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式穗熬,易于人閱讀和編寫
JSON 函數(shù)
使用 JSON 函數(shù)需要導(dǎo)入 json 庫:import json
函數(shù) | 描述 |
---|---|
json.dumps | 將 Python 對(duì)象編碼成 JSON 字符串 |
json.loads | 將已編碼的 JSON 字符串解碼為 Python 對(duì)象 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
# python字典
data = {
'id': 1,
'name': 'test1',
'age': '1'
}
# python列表
data2 = [{
'id': 1,
'name': 'test1',
'age': '1'
}, {
'id': 2,
'name': 'test2',
'age': '2'
}]
# python 字典轉(zhuǎn)json
json_str = json.dumps(data)
print(type(json_str))
print("python原始字典數(shù)據(jù):", repr(data)) # repr() 的作用是是將一個(gè)對(duì)象轉(zhuǎn)成字符串顯示,只做顯示用,repr()輸出對(duì) Python比較友好丁溅,repr()之后的字符串保證可以用eval()還原
print("字典轉(zhuǎn)成的json對(duì)象:", json_str)
# python 列表轉(zhuǎn)json
json_str2 = json.dumps(data2)
print(type(json_str2))
print("python原始列表數(shù)據(jù):", repr(data2)) # repr() 的作用是是將一個(gè)對(duì)象轉(zhuǎn)成字符串顯示,只做顯示用唤蔗,repr()輸出對(duì) Python比較友好,repr()之后的字符串保證可以用eval()還原
print("列表轉(zhuǎn)成的json對(duì)象:", json_str2)
# 將json對(duì)象轉(zhuǎn)換為python字典
data3 = json.loads(json_str)
print(data3)
# 將json對(duì)象轉(zhuǎn)換為python列表
data4 = json.loads(json_str2)
print(data4)
使用第三方庫:Demjson
如果沒有內(nèi)置Demjson庫窟赏,則需要通過pip安裝
JSON 函數(shù)
函數(shù) | 描述 |
---|---|
encode | 將 Python 對(duì)象編碼成 JSON 字符串 |
decode | 將已編碼的 JSON 字符串解碼為 Python 對(duì)象 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import demjson # 引入 demjson模塊
# 列表
datalist = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
# 字典
datadict = {'name':'mike','age':18}
# 列表轉(zhuǎn)json
jsonlist = demjson.encode(datalist)
print(jsonlist)
# 字典轉(zhuǎn)json
jsondict = demjson.encode(datadict)
print(jsondict)
Python XML
備注:xml有點(diǎn)麻煩妓柜,而且在目前前后端對(duì)接的過程中基本不用,就不展開了