python基礎學習筆記(十二)

來源:互聯網
上載者:User

標籤:start   匯入模組   stop   pytho   隨機數   鬥地主   nbsp   一點   檔案的   

模組

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

>>> import math>>> math.sin(0)  #sin為正弦函數0.0

 

模組是程式

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

#hello.pyprint "hello,world!"

下面通過python解譯器調用:

>>> import sys>>> sys.path.append(‘c:/python‘)>>> import hellohello,world!

再來一次:

>>> import hello>>> 

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

 

 

模組用於定義

1、在模組中定義函數

假設我們編寫了一個類似代碼的模組,將其儲存為hello2.py 檔案。

#hello2.pydef hello():    print "hello, world !"

儲存後,可以像下面這樣匯入:

>>> import hello2

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

>>> hello2.hello()

hello.world!

 

 

2、在模組中增加測試代碼

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

#hello3.pydef hello():    print "hello.world!"def test():    hello()if __name__ == ‘__main__‘: test()

f __name__ == ‘__nain__‘ 解釋

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

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

執行結果:

>>> import hello3   #表示hello3模組被調用,不執行test方法,所以沒有輸出>>> hello3.hello()   #表示程式執行,調用test方法hello.world!>>> hello3.hello()   #這裡是不是可以反覆調用test方法 hello.world!

 

 

 

讓模組可用

前面的例子中,我們改變了sys.path,其中包含了一個目錄列表,解譯器在該列表中尋找模組。在理想情況下,一開始sys.path本身就應該包含正確的目錄,有兩方法可以做到這一點: 一是將模組放置在合適的位置,別外一種是告訴解譯器去哪裡尋找需要的模組。

1、將模組放置在正確的位置

來看看python解譯器會從哪裡尋找模組

>>> import sys,pprint>>> pprint.pprint(sys.path)[‘‘, ‘I:\\Python27\\Lib\\idlelib‘, ‘C:\\Windows\\system32\\python27.zip‘, ‘I:\\Python27\\DLLs‘, ‘I:\\Python27\\lib‘, ‘I:\\Python27\\lib\\plat-win‘, ‘I:\\Python27\\lib\\lib-tk‘, ‘I:\\Python27‘, ‘I:\\Python27\\lib\\site-packages‘, ‘c:/python‘]

儘管這些目錄下都可以被找到,但site-packages 目錄是最佳選擇。

 

 

2、告訴編譯器去哪裡找

以下情況是告訴編譯器去哪兒找的原因:

  ** 不希望將自己的模組填滿python解譯器的目錄

  ** 沒有在python解譯器目錄中隱藏檔的許可權

  ** 想將模組放到其它位置

編輯sys.path ,前面就已經使用了

>>> import sys>>> sys.path.append(‘c:/python‘)

但更優雅的做法是配置pythonpath環境變數,方法和配置java 環境變數類似。

 

 

文檔

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

>>> print range.__doc__range([start,] stop[, step]) -> list of integersReturn 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函數的精確描述。

 

 

time 模組

time模組所包括的函數能夠實現 以下功能:獲得目前時間,操作時間和日期,從字串讀取時間以及格式化時間為字串。

time模組中重要的函數

 

 time.asctime將目前時間格式化為字串:

>>> time.asctime()‘Thu May 16 00:00:08 2013‘

 

 

 

random模組

random模組包括返回隨機的函數,可以用於類比或者用於任何產生隨機輸出的程式。

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

 

 

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

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

from random import *from time import *data1 = (2013 ,1,1,0,0,0,-1,-1,-1)time1 = mktime(data1)data2 = (2014 ,1,1,0,0,0,-1,-1,-1)time2 = mktime(data2)#然後在這個範圍內產生隨機數>>> random_time = uniform(time1,time2)# 可以將數字轉換成易讀的日期形式>>> print asctime(localtime(random_time))Fri Jan 18 18:23:16 2013

 

例2:下面一個例子,假設三個人打牌,首先要保證54張牌沒有重複的,第人發手裡18張(鬥地主就不能平均分配了)。

>>> values = range(1,13) + ‘dwang xwang‘.split()  #定義13個數字與大小王>>> 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 模組>>> pprint (deck [:18])         #輸出18張牌[‘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‘, ‘4 of hei‘, ‘4 of hong‘, ‘4 of mei‘, ‘4 of fang‘, ‘5 of hei‘, ‘5 of hong‘]

#顯然上面的輸出太整齊,調用隨機函數,隨機一點>>> from random import shuffle>>> shuffle(deck)>>> pprint(deck[:18])[‘5 of fang‘, ‘6 of hong‘, ‘5 of mei‘, ‘dwang of fang‘, ‘xwang of fang‘, ‘10 of hong‘, ‘7 of mei‘, ‘12 of hong‘, ‘6 of hei‘, ‘12 of hei‘, ‘7 of hei‘, ‘8 of hei‘, ‘4 of fang‘, ‘dwang of hei‘, ‘11 of hei‘, ‘12 of fang‘, ‘5 of hei‘, ‘2 of hong‘]

不過,依然是有問題的,大小王不應該分類型(黑、紅、梅、方),顯然上面的結果不夠完美。

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.