python基礎教程 模組和包的入方法

2021-10-09 07:15:59 字數 1374 閱讀 2932

一、模組的匯入

什麼是模組? 其實模組就是乙個py檔案。

模組的匯入方法有如下幾種,不同的匯入方法,模組裡的函式的使用方法各不相同。

1、import 模組名:

裡面函式的呼叫方法,模組名.函式名()

import time

time.sleep(

1)

2、from 模組名 import 函式名

函式呼叫方法:函式名()

from time import sleep

sleep(

1)

3、from 模組名 import *

函式呼叫方法:函式名()

from time import

*sleep(

1)

4、import 模組名 as 別名

函式呼叫方法:別名.函式名()

import time as t

t.sleep(

1)

接下來介紹一下__all__這個變數。使用方式如下:在模組檔案中加入__all__這個變數,實際上是乙個列表,裡面存放各個函式的名稱。當這個模組被用from 模組名 import * 這種方式呼叫時,__all__裡面有什麼函式就匯入什麼函式,如果沒定義__all__則預設匯入全部函式。

這是test模組

'''

'''def

printa()

:print

('aaaa'

)def

printb()

:print

('bbbb'

)__all__=

['printa'

]

下面是呼叫test

from test import

*printa(

)#aaaa

#如果呼叫,printb()則報錯

什麼是包?

所謂的包實際上就是幾個py檔案,並且包含乙個__init__檔案。

匯入包的方法如下:

1、from 包名 import 模組名

呼叫方法:模組名.函式名()

2、import 包名.模組名

呼叫方法:包名.模組名.函式名()

3、from 包名 import *

呼叫方法:模組名.函式名()

注:使用這個的前提是,在__init__檔案中寫入__all__變數,存放要匯入的模組名,不寫則預設什麼也不匯入

4、from 包名.模組名 import *

呼叫方法:函式名()

Python 基礎教程之包和類的用法

python 基礎教程之包和類的用法 建立乙個資料夾filepackage 在filepackage 資料夾內建立 init py 有了 init py filepackage才算是乙個包,否則只是算乙個普通資料夾。在filepackage 資料夾內建立 file.py file.py 如下 12 ...

python基礎教程

乙個簡單的客戶機 import socket s socket.socket host socket.gethostname port 1234 s.bind host,port s.listen 5 while true c,addr s.accept print got connection f...

Python基礎教程

本教程不包括python的安裝,ide採用spyder pytho2.7 1.print pow 2,3 8 print 2 3 8這裡pow函式表示乘方,與 功能相同。2.abs 10 10abs函式用來求乙個數的絕對值。3.round 0.6 1.0 round 0.4 0.0round函式將浮...