1.模塊
import 模塊名
1.1 模塊就是程序
任何python程序都可以作為模塊導(dǎo)入,并標(biāo)明程序(模塊)的位置
import sys
sys.path.append('路徑')
import hello // 在同一文件夾下
會(huì)在該文件夾里面自動(dòng)生成一個(gè)__pycache__
文件夾,包含處理后的文件。(可刪除,無(wú)影響)
在hello.py里面編寫函數(shù)
在t13.py里面調(diào)用模塊函數(shù)
import hello
hello.hello1()
運(yùn)行結(jié)果
hello
hello!
1.2 模塊屬性
1.2.1 name
檢查模塊是作為程序運(yùn)行還是被導(dǎo)入到另一個(gè)程序
如:在t13文件中,查看name屬性
print(__name__)
> __main__
在t13文件中,查看hello文件的name屬性
print(hello.__name__)
> __hello__
1.2.2 dir
查明模塊包含哪些東西,列出對(duì)象的所有屬性(函數(shù),類,變量)
print(dir(模塊名))
import box.shapes as sh
print(dir(sh))
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
1.2.3 變量__all__
用于指定一個(gè)模塊的所有公共接口(方法),只有被__all__
指定的接口,才可以被正確導(dǎo)入。
module.py
__all__ = ['foo', 'bar']
def foo():
print("This is foo!")
def bar():
print("This is bar!")
def baz():
print("This is baz!")
main.py
from module import *
foo()
bar()
baz()
運(yùn)行main.py結(jié)果
This is a foo!
This is bar!
NameError: name 'bar' is not defined
1.2.4 文檔__doc__
查看模塊信息和函數(shù)信息
print(range.__doc__)
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
自定義文檔字符串
通過(guò)三引號(hào)的方式添加
def plus(a, b):
'''This is a plus'''
print(a + b)
print(plus.__doc__)
> This is a plus
1.2.4 獲取模塊路徑__file__
可以獲取當(dāng)前模塊所在的目錄或文件的絕對(duì)路徑。
如main.py
print(__file__)
> d:\M\github\Python\Demo\main.py
還可以使用os.path
模塊的方法對(duì)路徑進(jìn)行處理,例如獲取當(dāng)前模塊所在目錄的絕對(duì)路徑:
import os
module_dir = os.path.dirname(os.path.abspath(__file__))
print(module_dir)
> d:\M\github\Python\Demo
2.包
包可以包含其他模塊,模塊存儲(chǔ)在擴(kuò)展名為.py的文件中,包則是一個(gè)目錄。
包必須包含有__init__.py
文件
在與文件夾box的同級(jí)文件下可以導(dǎo)入文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-581354.html
import box
import box.shapes
3.一些重要的模塊
3.1 sys
3.2 os
3.3 fileinput
3.4 集合,堆和雙端隊(duì)列
3.5 time
3.6 random
3.7 shelve和json
3.8 re
re,即正則表達(dá)式模塊文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-581354.html
到了這里,關(guān)于python筆記:第十章開(kāi)箱即用的模塊的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!