Q. Module
Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module.
A module is a file containing Python definitions and statements. Within a module, the module’s name (as a string) is available as the value of the global variable __name__
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module.
Ex. we had a fibo.py
. There are two functions fib(n)
and fib2(n)
we can use it like
import fibo
fibo.fib(1000)
fibo.fib2(100)
fib = fibo.fib
fib(500)
There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table
from fibo import fib, fib2
fib(500)
Q. Main module
Python modules are objects and have several useful attributes. All modules have a built-in attribute __name__
. you can also run the module directly as a standalone program, in which case __name__
will be a special default value, __main__
if __name__ == "__main__":
# main program here
Q. Package
使用 Python 時,你可以在開設的目錄中放個 __init__.py
檔案,這樣 Python 就會將這個目錄視為一個套件,而目錄名稱就是套件名稱。
使用 import pack.moduA
陳述時,Python 會尋找 pack
目錄,看看裏頭是否有 __init__.py
檔案,然後看看目錄中是否有個 moduA.py
檔案。__init__.py
檔案空白也無所謂,實際上當中也可以寫些程式碼,用來執行這個套件中都會需要的初始工作,不過慣例上,除非你有真正不得已的理由,請保持 __init__.py 檔案空白。