python學習筆記(模組、包、標準庫)

來源:互聯網
上載者:User

標籤:

模組

前面有簡單介紹如何使用import從外部模組擷取函數並且為自己的程式所用:

>>> import math
>>> math.sin(0)
0.0
>>>

模組是程式

任何python程式都可以作為模組匯入。假設寫如下程式,並且將它儲存為以F:\python\myDemo\hello.py

print ‘hello,world‘

下面通過python解譯器調用:

>>> import sys
>>> sys.path.append(‘F:\python\myDemo‘)

>>> import hello
hello,world

再匯入一次:

>>> import hello

>>>

怎麼這次沒結果?因為匯入模組並不意味著在匯入進執行某些操作。它們主要用於定義,比如變數、函數和類等。此外,因為只需要定義這些東西一次,匯入模組多次和匯入一次的效果是一樣的。

模組用於定義

在模組中定義函數

包含函數的簡單模組(儲存為hello2.py 檔案):

#hello2.py
def hello():
print ‘hello,world!‘

模組會被執行,這意味著hello函數在模組的作用被定義了。因此可以通過以下方式來訪問函數:

>>> import hello2
>>> hello2.hello()
hello,world!
>>>

在模組中增加測試代碼

 模組用來定義函數、類和其他內容,有時候在模組中添加一些檢查模組本身是否正常工作的測試代碼是非常有用的。 

#hello2.py
def hello():
print ‘hello,world!‘
def test():
hello()

if __name__==‘__main__‘:test()

---------------------

>>> import hello2
>>> hello2.hello()
hello,world!
>>> hello2.test()
hello,world!
>>>

f __name__ == ‘__nain__‘ 解釋:

python檔案的尾碼為.py ,.py檔案可以用來直接運行,就像一個獨立的小程式;也可以用來作為模組被其它程式調用。

__name__是模組的內建屬性,如果等於‘__main__‘ 側表示直接被使用,那麼將執行方法test()方法;如果是被調用則不執行 if 判斷後面的test()方法。

文檔

模組資訊的自然來源是文檔,除了通過python書籍或標準python文檔來查看某個函數的含義,也可以通過下面方式: 

>>> print range.__doc__
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
>>>

這樣就獲得了關於range函數的精確描述。

標準庫sys

sys模組能讓你訪問與Python解譯器聯絡緊密的函數和變數

>>> [n for n in dir(sys) if not n.startswith(‘_‘)]
[‘api_version‘, ‘argv‘, ‘builtin_module_names‘, ‘byteorder‘, ‘call_tracing‘, ‘callstats‘, ‘copyright‘, ‘displayhook‘, ‘dllhandle‘, ‘dont_write_bytecode‘, ‘exc_clear‘, ‘exc_info‘, ‘exc_traceback‘, ‘exc_type‘, ‘exc_value‘, ‘excepthook‘, ‘exec_prefix‘, ‘executable‘, ‘exit‘, ‘flags‘, ‘float_info‘, ‘float_repr_style‘, ‘getcheckinterval‘, ‘getdefaultencoding‘, ‘getfilesystemencoding‘, ‘getprofile‘, ‘getrecursionlimit‘, ‘getrefcount‘, ‘getsizeof‘, ‘gettrace‘, ‘getwindowsversion‘, ‘hexversion‘, ‘last_traceback‘, ‘last_type‘, ‘last_value‘, ‘long_info‘, ‘maxint‘, ‘maxsize‘, ‘maxunicode‘, ‘meta_path‘, ‘modules‘, ‘path‘, ‘path_hooks‘, ‘path_importer_cache‘, ‘platform‘, ‘prefix‘, ‘py3kwarning‘, ‘setcheckinterval‘, ‘setprofile‘, ‘setrecursionlimit‘, ‘settrace‘, ‘stderr‘, ‘stdin‘, ‘stdout‘, ‘subversion‘, ‘version‘, ‘version_info‘, ‘warnoptions‘, ‘winver‘]

os

os模組為你提供了訪問多個作業系統服務的功能

 fileinput

fileinput模組能夠遍曆文字檔的所有行

time

time模組包含的函數能夠獲得目前時間,操作時間和日期,從字串讀取時間及格式化時間為字串

>>> dir(time)
[‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘accept2dyear‘, ‘altzone‘, ‘asctime‘, ‘clock‘, ‘ctime‘, ‘daylight‘, ‘gmtime‘, ‘localtime‘, ‘mktime‘, ‘sleep‘, ‘strftime‘, ‘strptime‘, ‘struct_time‘, ‘time‘, ‘timezone‘, ‘tzname‘]
>>>

help(time)之後可以知道time有2種時間表示形式:
1、時間戳記標記法,即以整型或浮點型表示的是一個以秒為單位的時間間隔。這個時間的基礎值是從1970年的1月1號零點開始算起。
2、元組格式標記法,即一種python的資料結構表示。這個元組有9個整型內容。分別表示不同的時間含義。

(2008,1,21,21,2,56,0,21,0) #表示2008年1月21日21時2分56秒星期一,當年的第21天,無夏令時

year (four digits, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1) ##夏令時格式,0:表示正常格式,1:表示為夏令時格式,-1:表示根據當前的日期時間格式來判定

包含的函數:
time() -- 返回目前時間戳,浮點數形式。不接受參數
clock() -- 返回當前程式的cpu執行時間。unix系統始終返回全部已耗用時間;而windows從第二次開始都是以第一次調用此函數時的時間戳記作為基準,而不是程式開始時間為基準。不接受參數。
sleep() -- 延遲一個時間段,接受整型、浮點型。
gmtime() -- 將時間戳記轉換為UTC時間元組格式。接受一個浮點型時間戳記參數,其預設值為目前時間戳。
localtime() -- 將時間戳記轉換為本地時間元組格式。接受一個浮點型時間戳記參數,其預設值為目前時間戳。
asctime() -- 將時間元組格式轉換為字串形式。接受一個時間元組,其預設值為localtime()傳回值
ctime() -- 將時間戳記轉換為字串。接受一個時間戳記,其預設值為目前時間戳。等價於asctime(localtime(seconds))
mktime() -- 將本地時間元群組轉換為時間戳記。接受一個時間元組,必選。
strftime() -- 將時間元組以指定的格式轉換為字串形式。接受字串格式化串、時間元組。時間元組為可選,預設為localtime()
strptime() -- 將指定格式的時間字串解析為時間元組,strftime()的逆向過程。接受字串,時間格式2個參數,都是必選。
tzset() -- 改變本地時區。

例子:

將目前時間轉換為字串格式

>>> time.asctime()
‘Fri Aug 14 10:20:01 2015‘
>>>

時間字串支援的格式化符號

格式 含義 備忘
%a本地(locale)簡化星期名稱
%A本地完整星期名稱
%b本地簡化月份名稱
%B本地完整月份名稱
%c本地相應的日期和時間表示
%d一個月中的第幾天(01 - 31)
%H一天中的第幾個小時(24小時制,00 - 23)
%I第幾個小時(12小時制,01 - 12)
%j一年中的第幾天(001 - 366)
%m月份(01 - 12)
%M分鐘數(00 - 59)
%p本地am或者pm的相應符
%S秒(01 - 61)
%U一年中的星期數。(00 - 53星期天是一個星期的開始。)第一個星期天之前的所有天數都放在第0周。
%w一個星期中的第幾天(0 - 6,0是星期天)
%W和%U基本相同,不同的是%W以星期一為一個星期的開始。
%x本地相應日期
%X本地相應時間
%y去掉世紀的年份(00 - 99)
%Y完整的年份
%Z時區的名字(如果不存在為空白字元)
%%‘%’字元

random

random模組包含返回隨機數的函數,可以用於任何產生隨機輸出的程式

random模組中的一些重要函數:

下面介紹使用random模組的例子,還需要用到time模組中的函數。

例1:首先獲得代表時間間隔(2015年)限制的實數,這可以通過時間元組的方式來表示日期(使用 -1表示一周的某天,一年中某天和夏令時,以例讓python自己計算),並且對這些元組調用mktime :

from random import *
from time import *
date1=(2015,1,1,0,0,0,-1,-1,-1)
time1=mktime(date1)
date2=(2016,1,1,0,0,0,-1,-1,-1)
time2=mktime(date2)

random_time=uniform(time1,time2)#在這個範圍內均一的產生隨機數

print asctime(localtime(random_time))#將數字轉換為易讀的日期形式

----------

Fri Apr 03 22:56:16 2015
>>>

例2:下面一個例子,每次敲擊斷行符號鍵都為自己發一張牌,同時確保不會得到相同的牌。

values=range(1,11)+‘jack queen king‘.split()#定義十三張牌
suits=‘hei hong mei fang‘.split() #定義牌的四種類型
deck=[‘%s of %s‘ %(v,s) for v in values for s in suits]
from pprint import pprint
pprint (deck[:12])

---------------

>>>
[‘1 of hei‘,
‘1 of hong‘,
‘1 of mei‘,
‘1 of fang‘,
‘2 of hei‘,
‘2 of hong‘,
‘2 of mei‘,
‘2 of fang‘,
‘3 of hei‘,
‘3 of hong‘,
‘3 of mei‘,
‘3 of fang‘]
>>>

隨機擷取

values=range(1,11)+‘jack queen king‘.split()#定義十三張牌
suits=‘hei hong mei fang‘.split() #定義牌的四種類型
deck=[‘%s of %s‘ %(v,s) for v in values for s in suits]
from pprint import pprint
from random import shuffle
shuffle(deck)
pprint (deck[:12])

-------------

[‘1 of hong‘,
‘2 of mei‘,
‘queen of fang‘,
‘8 of mei‘,
‘4 of mei‘,
‘4 of fang‘,
‘king of hong‘,
‘2 of hei‘,
‘5 of fang‘,
‘king of fang‘,
‘jack of mei‘,
‘queen of hong‘]
>>>

按斷行符號鍵發牌

values=range(1,11)+‘jack queen king‘.split()#定義十三張牌
suits=‘hei hong mei fang‘.split() #定義牌的四種類型
deck=[‘%s of %s‘ %(v,s) for v in values for s in suits]
from pprint import pprint
from random import shuffle
shuffle(deck)
pprint (deck[1:1])

while deck:
raw_input(deck.pop())

shelve 

>>> import shelve
>>> s=shelve.open(‘test.dat‘)
>>> s[‘x‘]=[‘a‘,‘b‘,‘c‘]
>>> s[‘x‘].append(‘d‘)
>>> s[‘x‘]
[‘a‘, ‘b‘, ‘c‘]

d去哪了?
>>> temp=s[‘x‘]
>>> temp.append(‘d‘)
>>> s[‘x‘]=temp
>>> s[‘x‘]
[‘a‘, ‘b‘,‘c‘,‘d‘]

簡單的資料庫樣本

#database.py
import sys,shelve

def store_person(db):
pid =raw_input(‘enter unique ID number: ‘)
person={}
person[‘name‘]=raw_input(‘enter name: ‘)
person[‘age‘]=raw_input(‘enter age: ‘)
person[‘phone‘]=raw_input(‘enter phone number: ‘)

db[pid]=person

def lookup_person(db):
pid=raw_input(‘enter ID number: ‘)
field=raw_input(‘what would you like to know?(name,age,phone)‘)
field=field.strip().lower()
print field.capitalize()+‘:‘,db[pid][field]

def print_help():
print ‘the available commands are: ‘
print ‘store : stores informaion about a person‘
print ‘lookup :looks up a person from ID number‘
print ‘quit :save changes and exit‘
print ‘? : prints this message‘

def enter_command():
cmd=raw_input(‘enter command(? for help): ‘)
cmd=cmd.strip().lower()
return cmd

def main():
database=shelve.open(‘f:\\database.dat‘)
try:
while True:
cmd=enter_command()
if cmd==‘store‘:
store_person(database)
elif cmd==‘lookup‘:
lookup_person(database)
elif cmd==‘?‘:
print_help()
elif cmd==‘quit‘:
return
finally:
database.close()
if __name__==‘__main__‘: main()

------------------

enter command(? for help):
enter command(? for help): ?
the available commands are:
store : stores informaion about a person
lookup :looks up a person from ID number
quit :save changes and exit
? : prints this message
enter command(? for help): sotre
enter command(? for help): store
enter unique ID number: 002
enter name: xiao
enter age: 22
enter phone number: 110
enter command(? for help): lookup
enter ID number: 002
what would you like to know?(name,age,phone)phone
Phone: 110
enter command(? for help): quit
>>>

 

python學習筆記(模組、包、標準庫)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.