模塊與對象(六)

 

1.1 random模塊

import random

1.1.1 大於0且小於1之間的小數
print(random.random())

1.1.2 大於等於1且小於等於3之間的整數
print(random.randint(1,3))

1.1.3 大於等於1且小於3之間的整數
print(random.randrange(1,3))

1.1.4 1或者alex或者sb
print(random.choice([1,'alex','sb']))

1.1.5 列表元素任意2個組合
print(random.sample([1,'alex','sb'],2))

1.1.6 大於1小於4的小數,如1.927109612082716
print(random.uniform(1,4))

 

 

打亂數字順序python

l=[1,3,4,2,5]

random.shuffle(l)

print(l)

 

生成7位數校驗碼mysql

def make_code(n):

    res=''

    for i in range(n):

        s1=str(random.randint(0,9))

        s2=chr(random.randint(65,90))

        res+=random.choice([s1,s2])

    return res

 

print(make_code(7))

 

 

1.2 os模塊

os模塊是與操做系統交互的一個接口算法

1.2.1 os.stat('path/filename')  獲取文件/目錄信息

print(os.stat(r'F:\Python週末20期\day6\1 本節內容').st_size)   #文件大小sql

1.2.2 打印系統進程,無返回值

res=os.system('tasklist')

print('====>',res)

 

 

1.2.3 將path分割成目錄和文件名二元組返回

print(os.path.split(r'F:\Python週末20期\day6\1 本節內容'))

 

1.2.4 返回path的目錄。其實就是os.path.split(path)的第一個元素

print(os.path.dirname(r'F:\Python週末20期\day6\1 本節內容'))

 

1.2.5 返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素

print(os.path.basename(r'F:\Python週末20期\day6\1 本節內容'))

 

1.2.6 若是path是絕對路徑,返回True

print(os.path.isabs(r'C:\\a123sz'))

print(os.path.isabs(r'/root/a123sz'))

 

1.2.7 將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略

print(os.path.join('C:','D:\\','dir1','dir2','a.txt'))

print(os.path.join('D:\\','dir1','dir2','a.txt'))

 

1.2.8 在Linux和Mac平臺上,該函數會原樣返回path,在windows平臺上會將路徑中全部字符轉換爲小寫,並將全部斜槓轉換爲飯斜槓。

print(os.path.normcase('c:/windows\\SYstem32\\..'))

 

規範化路徑,如..和/shell

print(os.path.normpath('c://windows\\System32\\../Temp/')) #C:\windows\temp

 

 

1.2.9 os路徑處理

1.2.9.1  方式一:

F:\Python週末20期\day6\3 os模塊.py\..\..編程

print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

 

1.2.9.2  方式二:

BASE_DIR=os.path.normpath(os.path.join(

    os.path.abspath(__file__),

    '..',

    '..'

))

print(BASE_DIR)

 

1.2.10 返回path文件的大小

print(os.path.getsize(r'F:\Python週末20期\day6\1 本節內容'))

 

1.2.11 經常使用模塊

os.getcwd() 獲取當前工做目錄,即當前python腳本工做的目錄路徑json

os.chdir("dirname")  改變當前腳本工做目錄;至關於shell下cdwindows

os.curdir  返回當前目錄: ('.')bash

os.pardir  獲取當前目錄的父目錄字符串名:('..')網絡

os.makedirs('dirname1/dirname2')    可生成多層遞歸目錄

os.removedirs('dirname1')    若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推

os.mkdir('dirname')    生成單級目錄;至關於shell中mkdir dirname

os.rmdir('dirname')    刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname

os.listdir('dirname')    列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印

os.remove()  刪除一個文件

os.rename("oldname","newname")  重命名文件/目錄

os.stat('path/filename')  獲取文件/目錄信息

os.sep    輸出操做系統特定的路徑分隔符,win下爲"\\",Linux下爲"/"

os.linesep    輸出當前平臺使用的行終止符,win下爲"\t\n",Linux下爲"\n"

os.pathsep    輸出用於分割文件路徑的字符串 win下爲;,Linux下爲:

os.name    輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix'

os.system("bash command")  運行shell命令,直接顯示

os.environ  獲取系統環境變量

os.path.abspath(path)  返回path規範化的絕對路徑

os.path.split(path)  將path分割成目錄和文件名二元組返回

os.path.dirname(path)  返回path的目錄。其實就是os.path.split(path)的第一個元素

os.path.basename(path)  返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素

os.path.exists(path)  若是path存在,返回True;若是path不存在,返回False

os.path.isabs(path)  若是path是絕對路徑,返回True

os.path.isfile(path)  若是path是一個存在的文件,返回True。不然返回False

os.path.isdir(path)  若是path是一個存在的目錄,則返回True。不然返回False

os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略

os.path.getatime(path)  返回path所指向的文件或者目錄的最後存取時間

os.path.getmtime(path)  返回path所指向的文件或者目錄的最後修改時間

os.path.getsize(path) 返回path的大小

 

1.3 sys模塊

sys.argv           命令行參數List,第一個元素是程序自己路徑

sys.exit(n)        退出程序,正常退出時exit(0)

sys.version        獲取Python解釋程序的版本信息

sys.maxint         最大的Int值

sys.path           返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值

sys.platform       返回操做系統平臺名稱

import sys

sys.argv

sys.exit(0)

sys.path

 

 

進度條的效果制定寬度

print('[%-50s]' %('#'*1))

print('[%-50s]' %('#'*2))

print('[%-50s]' %('#'*3))

print('[%-50s]' %('#'*4))

print('[%-50s]' %('#'*5))

 

打印%

([%-50s]) %('#'*10)

print('[%%-%ds]' %50) #'[%-50s]'

 

可傳參來控制寬度

print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)

print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)

print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)

print(('[%%-%ds]' %50) %('#'*10)) #'[%-50s]' %('#'*10)

 

打印%
print('%d%%' %30)

 

1.3.1 進度條功能

import time 

#指定寬度

print('[%-15s]' %'#')

print('[%-15s]' %'##')

print('[%-15s]' %'###')

print('[%-15s]' %'####') 

 

#打印%

print('%s%%' %(100)) #第二個%號表明取消第一個%的特殊意義 

#可傳參來控制寬度

print('[%%-%ds]' %50) #[%-50s]

print(('[%%-%ds]' %50) %'#')

print(('[%%-%ds]' %50) %'##')

print(('[%%-%ds]' %50) %'###')

 

#實現打印進度條函數

import sys

import time

 

def progress(percent,width=50):

    if percent >= 1:

        percent=1

    show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')

    print('\r%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')

 

 

應用

def progress(percent,width=50): #進度條的寬度70

    if percent >= 1:

        percent=1

    show_str = ('[%%-%ds]' % width) % ('#' * int(width*percent))

    print('\r%s %d%%' %(show_str,int(100*percent)),end='')

 

recv_size=0

total_size=10241

while recv_size < total_size:

    time.sleep(0.1) #模擬數據的傳輸延遲

    recv_size+=1024 #每次收1024

    progress(recv_size/total_size) #接收的比例

 

 

1.4 shutil模塊

高級的 文件、文件夾、壓縮包 處理模塊

1.4.1 shutil.copyfileobj(fsrc, fdst[, length])

將文件內容拷貝到另外一個文件中

import shutil

shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

shutil.copyfile(src, dst)

 

1.4.2 拷貝文件

shutil.copyfile('f1.log', 'f2.log') #目標文件無需存在

shutil.copymode(src, dst) 僅拷貝權限。內容、組、用戶均不變

shutil.copymode('f1.log', 'f2.log') #目標文件必須存在

shutil.copystat(src, dst) 僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags

shutil.copystat('f1.log', 'f2.log') #目標文件必須存在

1.4.2.1  shutil.copy(src, dst)

import shutil

shutil.copy('f1.log', 'f2.log') 拷貝文件和權限

import shutil

shutil.copy2('f1.log', 'f2.log') 拷貝文件和狀態信息 

1.4.2.2  shutil.ignore_patterns(*patterns)

shutil.copytree(src, dst, symlinks=False, ignore=None)

遞歸的去拷貝文件夾

import shutil

shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目標目錄不能存在,注意對folder2目錄父級目錄要有可寫權限,ignore的意思是排除 

1.4.2.3  拷貝軟鏈接

import shutil

 

shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

 

'''

一般的拷貝都把軟鏈接拷貝成硬連接,即對待軟鏈接來講,建立新的文件

'''

 

1.4.3 shutil.rmtree(path[, ignore_errors[, onerror]])

遞歸的去刪除文件

import shutil

shutil.rmtree('folder1')

 

 

1.4.4 shutil.move(src, dst)

遞歸的去移動文件,它相似mv命令,其實就是重命名。

import shutil

shutil.move('folder1', 'folder3')

 

 

1.4.5 壓縮解壓縮

1.4.5.1  shutil.make_archive(base_name, format,...)

建立壓縮包並返回文件路徑,例如:zip、tar

建立壓縮包並返回文件路徑,例如:zip、tar

base_name: 壓縮包的文件名,也能夠是壓縮包的路徑。只是文件名時,則保存至當前目錄,不然保存至指定路徑,

如 data_bak                       =>保存至當前路徑

如:/tmp/data_bak =>保存至/tmp/

format:      壓縮包種類,「zip」, 「tar」, 「bztar」,「gztar」

root_dir:    要壓縮的文件夾路徑(默認當前目錄)

owner:       用戶,默認當前用戶

group: 組,默認當前組

logger:       用於記錄日誌,一般是logging.Logger對象

import shutil

shutil.make_archive("bak", 'gztar', root_dir=r'F:\Python週末20期\day6') #tar cvzf bak.tar.gz /root

 

 

#將 /data 下的文件打包放置當前程序目錄

import shutil

ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')

 

#將 /data下的文件打包放置 /tmp/目錄

import shutil

ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

 

 

1.4.5.2  zipfile壓縮解壓縮

import zipfile

 

# 壓縮

z = zipfile.ZipFile('laxi.zip', 'w')

z.write('a.log')

z.write('data.data')

z.close()

 

# 解壓

z = zipfile.ZipFile('laxi.zip', 'r')

z.extractall(path='.')

z.close()

 

1.4.5.3  tarfile壓縮解壓縮

import tarfile

 

# 壓縮

>>> t=tarfile.open('/tmp/egon.tar','w')

>>> t.add('/test1/a.py',arcname='a.bak')

>>> t.add('/test1/b.py',arcname='b.bak')

>>> t.close()

壓縮

import tarfile

t=tarfile.open('bak.tar.gz')

t.extractall(r'F:\Python週末20期\day6\aaa')

t.close()

 

# 解壓

>>> t=tarfile.open('/tmp/egon.tar','r')

>>> t.extractall('/egon')

>>> t.close()

 

 

 

1.5 jison和pickle模塊

以前咱們學習過用eval內置方法能夠將一個字符串轉成python對象,不過,eval方法是有侷限性的,對於普通的數據類型,json.loads和eval都能用,但遇到特殊類型的時候,eval就無論用了,因此eval的重點仍是一般用來執行一個字符串表達式,並返回表達式的值

dic={'a':1}

 

with open('db.txt','w',encoding='utf-8') as f:

    f.write(str(dic))

 

with open('db.txt','r',encoding='utf-8') as f:

    dic=eval(f.read()) #"{'a':1}"

    print(dic['a'])

打印報錯

eval("[null,false,1]")

 

 

沒法解析null類型,而json就能夠

import json

dic={'a':1}

x=None

 

res1=json.dumps(dic) #str(dic)

res2=str(dic)

print(res1,type(res1))

print(res2,type(res2))

 

res=json.dumps(x)

print(res,type(res))

 

 

1.5.1 json序列化

若是咱們要在不一樣的編程語言之間傳遞對象,就必須把對象序列化爲標準格式,好比XML,但更好的方法是序列化爲JSON,由於JSON表示出來就是一個字符串,能夠被全部語言讀取,也能夠方便地存儲到磁盤或者經過網絡傳輸。JSON不只是標準格式,而且比XML更快,並且能夠直接在Web頁面中讀取,很是方便。

JSON表示的對象就是標準的JavaScript語言的對象,JSON和Python內置的數據類型對應以下:

 

 

圖1-1  

 

 

圖1-2  

 

 

import json,time

user={'name':'egon','age':18,'nb':True}

with open('user.json','w',encoding='utf-8') as f:

    f.write(json.dumps(user))  #等價於json.dump(dic,f)

 

students=['alex','egon','wxx','yxx']

json.dump(students,open('students.json','w',encoding='utf-8'))

 

time.sleep(500)

 

 

1.5.2 pickle

 

 

圖1-3  

Pickle的問題和全部其餘編程語言特有的序列化問題同樣,就是它只能用於Python,而且可能不一樣版本的Python彼此都不兼容,所以,只能用Pickle保存那些不重要的數據,不能成功地反序列化也不要緊。

 

import pickle,json

import pickle,json

 

s={1,2,3}

print(json.dumps(s))

print(pickle.dumps(s))

 

with open('s.pkl','wb') as f:  #注意是w是寫入str,wb是寫入bytes,j是'bytes'

    f.write(pickle.dumps(s))

 

pickle.dump(s,open('s.pkl','wb'))

 

 

 

 

1.5.3 json反序列化

with open('s.pkl','rb') as f:

    s=pickle.loads(f.read()) #等價於s=pickle.load(f)

    print(s,type(s))

 

s=pickle.load(open('s.pkl','rb'))

print(s, type(s))

 

不管數據是怎樣建立的,只要知足json格式,就能夠json.loads出來,不必定非要dumps的數據才能loads

1.6 shelve模塊

shelve模塊比pickle模塊簡單,只有一個open函數,返回相似字典的對象,可讀可寫;key必須爲字符串,而值能夠是python所支持的數據類型

import shelve

 

f=shelve.open('db.shl')

# f['stu1']={'name':'alex1','age':38}

# f['stu2']={'name':'alex2','age':28}

print(f['stu1']['name'])

f.close()

 

 

1.7 xml模塊

xml是實現不一樣語言或程序之間進行數據交換的協議,跟json差很少,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,你們只能選擇用xml呀,至今不少傳統公司如金融行業的不少系統的接口還主要是xml。

xml數據

<?xml version="1.0"?>

<data>

    <country name="Liechtenstein">

        <rank updated="yes">2</rank>

        <year>2008</year>

        <gdppc>141100</gdppc>

        <neighbor name="Austria" direction="E"/>

        <neighbor name="Switzerland" direction="W"/>

    </country>

    <country name="Singapore">

        <rank updated="yes">5</rank>

        <year>2011</year>

        <gdppc>59900</gdppc>

        <neighbor name="Malaysia" direction="N"/>

    </country>

    <country name="Panama">

        <rank updated="yes">69</rank>

        <year>2011</year>

        <gdppc>13600</gdppc>

        <neighbor name="Costa Rica" direction="W"/>

        <neighbor name="Colombia" direction="E"/>

    </country>

</data>

 

xml協議在各個語言裏的都 是支持的,在python中能夠用如下模塊操做xml:

# print(root.iter('year')) #全文搜索

# print(root.find('country')) #在root的子節點找,只找一個

# print(root.findall('country')) #在root的子節點找,找全部

from xml.etree import ElementTree

 

tree=ElementTree.parse('a.xml')

 

root=tree.getroot()

print(root.tag)

print(root.attrib)

print(root.text)

 

 

三種查找方式

從子節點中找

print(root.find('country'))

print(root.findall('country'))

print(root.find('rank')) #None

 

 

從正樹形結構中查找

print(list(root.iter('rank')))

 

for country in root.findall('country'):

    rank=country.find('rank')

    print(rank.tag,rank.attrib,rank.text)

 

 

遍歷文檔樹

for country in root:

    print('=============>',country.attrib['name'])

    for item in country:

        print(item.tag,item.attrib,item.text)

 

 

for year in root.iter('year'):

    print(year.tag,year.attrib,year.text)

 

 

for year in root.iter('year'):

    year.set('updated',"yes")

    year.text=str(int(year.text)+1)

 

tree.write('a.xml')

 

#在country內添加(append)節點

for country in root:

    obj=ElementTree.Element('egon') #<egon name="egon" age="18">egon is good</egon>

    obj.attrib={'name':'egon','age':'18'}

    obj.text='egon is good'

    country.append(obj)

 

tree.write('a.xml')

 

for rank in root.iter('rank'):

    if int(rank.text) == 5:

        obj=ElementTree.Element('egon') #<egon name="egon" age="18">egon is good</egon>

        obj.attrib={'name':'egon','age':'18'}

        obj.text='egon is good'

        rank.append(obj)

 

tree.write('a.xml')

 

 

1.8 configerparser模塊

import configparser

 

config=configparser.ConfigParser()

config.read('my.ini')

#查看全部的標題

print(config.sections())

#查看標題mysqld下全部key=value的key

print(config.options('mysqld'))

#查看標題mysqld下charater-server-set的值=>字符串格式

print(config.get('mysqld','charater-server-set'))

 

if config.has_option('mysqld','aaa'):

    print(config.get('mysqld','aaa'))

查看標題mysqld下'skip-grant-table的值=>布爾值格式

print(config.getboolean('mysqld','skip-grant-table'))

查看標題mysqld'下port的值=>整數格式

print(config.getint('mysqld','port'))

查看標題mysqld'下port的值=> >浮點型格式
print(config.getfloat('mysqld','port'))

添加一個標題

config.add_section('egon')

在標題egon下添加name=egon,age=18的配置

config.set('egon','name','egon')

config.set('egon','age','18')

config.set('client','password','alex3714')

最後將修改的內容寫入文件,完成最終的修改

config.write(open('my.ini','w',encoding='utf-8'))

 

 

1.9 hashlib模塊

hash:一種算法 ,3.x裏代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

1.9.1 三個特色:

1.內容相同則hash運算結果相同,內容稍微改變則hash值則變

2.不可逆推

3.相同算法:不管校驗多長的數據,獲得的哈希值長度固定。

m=hashlib.md5()

m.update('hello'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

m.update('world'.encode('utf-8'))

print(m.hexdigest())

 

fc5e038d38a57032085441e7fe7010b0

 

 

 

m=hashlib.md5()

m.update('hello'.encode('utf-8'))

m.update('world'.encode('utf-8'))

print(m.hexdigest())

 

m1=hashlib.md5()

m1.update('hellowor'.encode('utf-8'))

m1.update('l'.encode('utf-8'))

m1.update('d'.encode('utf-8'))

print(m1.hexdigest()) 
注意:把一段很長的數據update屢次,與一次update這段長數據,獲得的結果同樣
18 可是update屢次爲校驗大文件提供了可能。
name=input('user:>> ')

pwd=input('password:>> ')

m=hashlib.md5()

m.update(pwd.encode('utf-8'))

pwd=m.hexdigest()

 

print(name,pwd)

 

1.9.2 模擬撞庫

cryt_pwd='aee949757a2e698417463d47acac93df'

pwds=[

    'alex3714',

    'alex123',

    '123alex'

]

def make_dic(pwds):

    dic={}

    for pwd in pwds:

        m=hashlib.md5(pwd.encode('utf-8'))

        dic[pwd]=m.hexdigest()

    return dic

 

dic=make_dic(pwds)

for pwd in dic:

    if dic[pwd] == cryt_pwd:

        print(pwd)

 

 

以上加密算法雖然依然很是厲害,但時候存在缺陷,即:經過撞庫能夠反解。因此,有必要對加密算法中添加自定義key再來作加密

import hashlib

 

m=hashlib.sha512()

m=hashlib.md5('一行白鷺上青天'.encode('utf-8'))

m.update('alex3714'.encode('utf-8'))

m.update('兩個黃鸝鳴翠柳'.encode('utf-8'))

print(m.hexdigest())

python 還有一個 hmac 模塊,它內部對咱們建立 key 和 內容 進行進一步的處理而後再加密:
import hmac

m=hmac.new('加鹽'.encode('utf-8'))

m.update('alex3714'.encode('utf-8'))

print(m.hexdigest())

 

#要想保證hmac最終結果一致,必須保證:

#1:hmac.new括號內指定的初始key同樣

#2:不管update多少次,校驗的內容累加到一塊兒是同樣的內容

import hmac

 

h1=hmac.new(b'egon')

h1.update(b'hello')

h1.update(b'world')

print(h1.hexdigest())

 

h2=hmac.new(b'egon')

h2.update(b'helloworld')

print(h2.hexdigest())

 

h3=hmac.new(b'egonhelloworld')

print(h3.hexdigest())

 

'''

f1bf38d054691688f89dcd34ac3c27f2

f1bf38d054691688f89dcd34ac3c27f2

bcca84edd9eeb86f30539922b28f3981

'''

 

1.10 subprocess模塊

import subprocess

import time

 

subprocess.Popen('tasklist',shell=True)

print('----->主')

time.sleep(1)

 

import time

import subprocess

 

 

obj=subprocess.Popen('tasklist',shell=True,

                 stdout=subprocess.PIPE,

                 stderr=subprocess.PIPE,

                 )

print(obj)

print('第1次:',obj.stdout.read())

print('第2次:',obj.stdout.read())

print('---->主')

 

print(obj.stdout.read().decode('gbk'))

 

 

#等同於上面,可是上面的優點在於,一個數據流能夠和另一個數據流交互,能夠經過爬蟲獲得結果真後交給grep
import subprocess #ls /etc ;pwd;ps aux

obj=subprocess.Popen('tssssasklist',shell=True,

                 stdout=subprocess.PIPE,

                 stderr=subprocess.PIPE,

                 )

 

print(obj.stdout.read())

print(obj.stderr.read().decode('gbk'))

 

瞭解

import subprocess #tasklist | findstr python

obj=subprocess.Popen('tasklist | findstr python',shell=True,

                 stdout=subprocess.PIPE,

                 stderr=subprocess.PIPE,

                 )

 

print(obj.stdout.read())

 

 

obj1=subprocess.Popen('tasklist',shell=True,

                 stdout=subprocess.PIPE,

                 stderr=subprocess.PIPE,

                 )

 

obj2=subprocess.Popen('findstr python',shell=True,

                 stdin=obj1.stdout,

                 stdout=subprocess.PIPE,

                 stderr=subprocess.PIPE,

                 )

 

print(obj2.stdout.read())  #subprocess使用當前系統默認編碼,獲得結果爲bytes類型,在windows下須要用gbk解碼

 

 

面向對象

1.11 類的定義與使用

1.11.1 面向過程與面向對象

    面向過程:核心是過程二字,過程即解決問題的步驟,就是先幹什麼再幹什麼

    基於該思想寫程序就比如在設計一條流水線,是一種機械式的思惟方式

    優勢:複雜的過程流程化,進而簡單化

    缺點:擴展性差

 

    面向對象:核心是對象二字,對象是特徵與技能的結合體

    基於該思想編寫程序就比如在創造一個世界,世界是由一個個對象組成,是一種「上帝式」的思惟方式

    優勢:可擴展性強

    缺點:編程複雜高,容易出現過分設計

 

1.11.2 類

    對象是特徵與技能的結合體,類就是一系列對象類似的特徵與技能的結合體

    在現實世界中:必定是先有的一個個具體存在的對象,後總結出的類

    在程序中:必定保證先定義類,後產生對象

 

1.11.3 站在老男孩學校的角度

現實中的對象:

    對象1:

        特徵

            學校=老男孩

            名字=李三炮

            性別=男

            年齡=18

        技能

            學習

            選課

 

    對象2:

        特徵

            學校=老男孩

            名字=張鐵蛋

            性別=女

            年齡=38

        技能

            學習

            選課

 

    對象3:

        特徵

            學校=老男孩

            名字=武大郎

            性別=男

            年齡=28

        技能

            學習

            選課

 

    對象4:

        特徵

            學校=老男孩

            名字=egon

            性別=男

            年齡=18

        技能

            教學

 

 

現實中的老男孩學生類:

    老男孩學生類

        類似的特徵

            學校=老男孩

        類似的技能

            學習

            選課

 

'''

# 類體代碼在類的定義階段就會馬上執行,

class Student:

    school='oldboy'

 

    def learn(self):

        print('is learning')

 

    def choose_course(self):

        print('choose course')

 

    # print('====run')

 

 

# print(Student)

# print(Student.__dict__)

 

#查看

# print(Student.school) #數據屬性

# print(Student.learn) #函數屬性

 

#增長

# Student.country='China'

# print(Student.country)

 

#修改

# Student.school='Oldboy'

# print(Student.school)

 

#刪除

# del Student.country

# print(Student.country)

 

# print(Student.learn)

# Student.learn('xxxxx')

 

 

1.12 對象的定義與使用

1.12.1 面向過程與面向對象

    面向過程:核心是過程二字,過程即解決問題的步驟,就是先幹什麼再幹什麼

    基於該思想寫程序就比如在設計一條流水線,是一種機械式的思惟方式

    優勢:複雜的過程流程化,進而簡單化

    缺點:擴展性差

 

    面向對象:核心是對象二字,對象是特徵與技能的結合體

    基於該思想編寫程序就比如在創造一個世界,世界是由一個個對象組成,是一種「上帝式」的思惟方式

    優勢:可擴展性強

    缺點:編程複雜高,容易出現過分設計

 

1.12.2 類

    對象是特徵與技能的結合體,類就是一系列對象類似的特徵與技能的結合體

    在現實世界中:必定是先有的一個個具體存在的對象,後總結出的類

    在程序中:必定保證先定義類,後產生對象

 

1.12.3 站在老男孩學校的角度

現實中的對象:

    對象1:

        特徵

            學校=老男孩

            名字=李三炮

            性別=男

            年齡=18

        技能

            學習

            選課

 

    對象2:

        特徵

            學校=老男孩

            名字=張鐵蛋

            性別=女

            年齡=38

        技能

            學習

            選課

 

    對象3:

        特徵

            學校=老男孩

            名字=武大郎

            性別=男

            年齡=28

        技能

            學習

            選課

 

    對象4:

        特徵

            學校=老男孩

            名字=egon

            性別=男

            年齡=18

        技能

            教學

 

 

現實中的老男孩學生類:

    老男孩學生類

        類似的特徵

            學校=老男孩

        類似的技能

            學習

            選課

 

'''

class Student:

    school='oldboy'

 

    #stu1,'李三炮','男',18

    def __init__(self,name,sex,age): #在調用類時會自動觸發執行

        self.Name=name

        self.Sex=sex

        self.Age = age

 

        #stu1.Name='李三炮'

        #stu1.Sex='男'

        #stu1.Age=18

 

    def learn(self):

        print('is learning')

 

    def choose_course(self):

        print('choose course')

 

#調用類的過程又稱之爲實例化:stu1=Student('李三炮','男',18)

#一、獲得一個返回值,即對象,該對象是一個空對象stu1

#二、Student.__init__(stu1,'李三炮','男',18)

 

stu1=Student('李三炮','',18)

# print(stu1.__dict__)

# print(stu1.Name,stu1.Age,stu1.Sex)

 

stu2=Student('張鐵蛋','',38)

stu3=Student('武大郎','',28)

# print(stu2.__dict__)

# print(stu3.__dict__)

 

# print(stu1,stu2,stu3)

 

# print(stu2.Name)

 

 

 

1.13 屬性查找與綁定方法

x=1

class Student:

    school='oldboy'

    # Name='xxx'

 

    def __init__(self,name,sex,age): #在調用類時會自動觸發執行

        self.Name = name

        self.Sex = sex

        self.Age = age

 

 

        #stu1.Name='李三炮'

        #stu1.Sex='男'

        #stu1.Age=18

 

    def learn(self,x,y):

        print('%s is learning' %self.Name)

        print(x,y)

 

    def choose_course(self):

        print('choose course')

 

    def commit_hw():

        print('commit homework')

 

 

1.13.1 查找一個對象的屬性順序是:先找對象本身的__dict__,再找類的__dict__

# stu1=Student('李三炮','男',18)

# # print(stu1.__dict__)

#

# # print(stu1.Name)

# # print(stu1.school)

# # print(stu1.x)

 

stu1=Student('李三炮','',18)

stu2=Student('張鐵蛋','',38)

stu3=Student('武大郎','',28)

 

 

1.13.2 類的數據屬性是全部對象共享,全部對象都指向同一個內存地址

# stu1.school='xxx'

# Student.school='Oldgirl'

# print(Student.school,id(Student.school))

# print(stu1.school,id(stu1.school))

# print(stu2.school,id(stu2.school))

# print(stu3.school,id(stu3.school))

 

 

# 三、類中定義的函數是綁定給對象使用:

# 3.1:不一樣對象就是不一樣綁定方法

# 3.2:綁定給誰,就應該由誰來調用,誰來調用就會把誰當作第一個參數傳給對應的函數

# print(Student.learn)

# print(stu1.learn)

# print(stu2.learn)

# print(stu3.learn)

 

# stu1.learn(1,2) #Student.learn(stu1,1,2)

# stu2.learn(1,3)

# stu3.learn(1,4)

# print(Student.learn)

 

# stu1.commit_hw()

 

 

1.13.3 小練習

class Teacher:

    school='oldboy'

    count=0

 

    def __init__(self,name,sex,age,level,salary):

        self.name=name

        self.sex=sex

        self.age=age

        self.level=level

        self.salary=salary

        Teacher.count+=1

 

    def teach(self):

        print('%s is teaching' %self.name)

 

t1=Teacher('egon','male',18,10,3000)

t2=Teacher('alex','female',38,9,30000)

t3=Teacher('wxx','female',28,10,30000)

 

print(t1.count)

print(t2.count)

print(t3.count)

 

 

 

class Garen:

    camp='demacia'

    def __init__(self,nickname,life_value,aggresivity):

        self.nickname=nickname

        self.life_value=life_value

        self.aggresivity=aggresivity

 

    def attack(self,enemy):

        enemy.life_value-=self.aggresivity

 

 

class Riven:

    camp = 'Noxus'

 

    def __init__(self, nickname, life_value, aggresivity):

        self.nickname = nickname

        self.life_value = life_value

        self.aggresivity = aggresivity

 

    def attack(self, enemy):

        enemy.life_value -= self.aggresivity

 

    def fire(self,enemy):

        enemy.life_value-=100

 

g1=Garen('草叢猥瑣男',1000,100)

r1=Riven('猛男雯雯',200,500)

print(r1.life_value)

g1.attack(r1)

print(r1.life_value)

 

 

1.14 類即類型

# class Teacher:

#     school='oldboy'

#     count=0

#

#     def __init__(self,name,sex,age,level,salary):

#         self.name=name

#         self.sex=sex

#         self.age=age

#         self.level=level

#         self.salary=salary

#         Teacher.count+=1

#

#     def teach(self):

#         print('%s is teaching' %self.name)

#

# t1=Teacher('egon','male',18,10,3000)

# print(type(t1))

 

# l=[1,2,3,4] #l=list([1,2,3,4])

# print(type(l))

 

l1=list([1,2,3,4])

l2=list([1,2,3,4])

# print(id(l1))

# print(id(l2))

 

# print(l1.append)

# l1.append(5) #list.appent(l1,5)

# list.append(l1,5)

# print(l1)

 

l1.append('a')

l2.append('b')

 

 

1.15 從代碼級別看面向對象

1.15.1 在沒有學習類這個概念時,數據與功能是分離的

def exc1(host,port,db,charset,sql):

    conn=connect(host,port,db,charset)

    res=conn.execute(sql)

    return res

 

def exc2(host,port,db,charset,proc_name)

    conn=connect(host,port,db,charset)

    res=conn.call_proc(prco_name)

    return res

 

 

#每次調用都須要重複傳入一堆參數

exc1('127.0.0.1',3306,'db1','utf8','select * from tb1;')

exc2('127.0.0.1',3306,'db1','utf8','存儲過程的名字')

 

exc1('127.0.0.1',3306,'db1','utf8','select * from tb2;')

 

 

1.15.2 在沒有學習類這個概念時,數據與功能是分離的

host='127.0.0.1'

port=3306

db='db1'

charset='utf-8'

 

x=1

y=2

 

def exc1(sql):

    conn=connect(host,port,db,charset)

    res=conn.execute(sql)

    return res

 

def exc2(proc_name)

    conn=connect(host,port,db,charset)

    res=conn.call_proc(prco_name)

    return res

 

def func1():

    print(x)

    print(y)

 

def func2():

    print(x)

    print(y)

 

 

#每次調用都須要重複傳入一堆參數

exc1('select * from tb1;')

exc2('utf8','存儲過程的名字')

 

exc1('select * from tb2;')

 

func()

 

1.15.3 使用類

# class Mysqlhandle:

#     def __init__(self,host,port,db,charset='utf-8'):

#         self.host=host

#         self.port=port

#         self.db=db

#         self.charset=charset

#         self.conn=connect(host,port,db,charset)

#

#     def exc1(self,sql):

#         return self.conn.execute(sql)

#

#     def exc2(self,proc_name)

#         return self.conn.call_proc(prco_name)

#

# obj1=Mysqlhandle('127.0.0.1',3306,'db1')

#

# obj1.exc1('select * from t1')

# obj1.exc1('select * from t2')

# obj1.exc1('select * from t3')

 

# obj2=Mysqlhandle('10.10.10.9',3306,'db2')

# obj2.exc1('select * from t1 where id > 3')
相關文章
相關標籤/搜索