Python 3.1 快速導覽 - 模組

一個 .py 檔案就是一個模組 (module) ,例如以下程式

class Demo:
    __x = 0

    def __init__(self, i):
        self.__i = i
        Demo.__x += 1
    
    def __str__(self):
        return str(self.__i)
         
    def hello(self):
        print("hello " + self.__str__())
    
    @classmethod 
    def getX(cls):
        return cls.__x

class Other:
    def __init__(self, k):
        self.k = k

    def __str__(self):
        return str(self.k)

    def hello(self):
        print("hello, world")
    
    def bye(self):
        print("Good-bye!", self.__str__())

class SubDemo(Demo, Other):
    def __init__(self, i, j):
        super().__init__(i)
        self.__j = j
    
    def __str__(self):
        return super().__str__() + "+" + str(self.__j)

a = SubDemo(12, 34)
a.hello()
a.bye()
b = SubDemo(56, 78)
b.hello()
b.bye()

# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla21.py
# 功能:示範 Python 程式 
# 作者:張凱慶
# 時間:西元 2010 年 12 月


cla21.py 即是一個模組,我們可以在其他 Python 程式檔案中使用 cla21.py 所定義的類別,最簡單的方式就是利用關鍵字 (keyword) import 引入 cla21.py 的內容,如下
import cla21


引入模組名稱不需要 .py 的副檔名,使用檔名 cla21 即可,引入後便可使用 cla21 所定義的內容,如下
import cla21

a = cla21.SubDemo(12, 34)
a.hello()
a.bye()
b = cla21.SubDemo(56, 78)
b.hello()
b.bye()

# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:mod01.py
# 功能:示範 Python 程式 
# 作者:張凱慶
# 時間:西元 2010 年 12 月


注意兩個,首先, mod01.py 與 cla21.py 必須在相同資料夾內,其次,第三行
a = cla21.SubDemo(12, 34)


利用 import 引入 cla21 所定義的類別 SubDemo ,須連用模組名稱 cla21 ,以辨明是哪個模組。這裡,若是我們想要直接使用類別 SubDemo 的名稱,我們可以連用另一個關鍵字 from ,例如
from cla21 import *


星號表示所有的內容,如果不寫星號,就得把 SubDemo 寫出來,例如
from cla21 import SubDemo


因此,當引入的名稱數量很多時,星號可以省下許多打字的時間。


mod01.py 執行結果如下



總共執行了兩次,這是為什麼呢?因為 cla21.py 有沒有縮排的程式碼,所以執行 import 的時候就先執行 cla21.py 中沒有縮排的程式碼。


如果模組中除了類別、函數或其他的定義外,還具有可執行的程式碼,我們不打算在引入模組後執行這些程式碼的話,當作模組的檔案,於可執行程式碼前應該加入額外 if 陳述 (statement) ,如下
if __name__ == "__main__":
    #模組中可執行的程式碼


__name__ 是模組特別的屬性 (attribute) ,當 Python 檔案以直譯器直接執行時, __name__ 就會被設置成 "__main__" ,因此只有當此模組直接被執行, if 陳述底下的程式碼才會執行,若是在其他 Python 檔案中引入該模組,直譯器就會跳過這段 if 陳述。


中英文術語對照
模組module
關鍵字keyword
陳述statement
屬性attribute






4 則留言:

高藥師 提到...

請問怎麼知道python 有哪些"內建模組"

我現在只看到大家都舉例 math

那能知道哪些內建模組或者這些模組的功用嗎

謝謝!

Kaiching Chang 提到...

完整內建模組請參考官方的 Library Reference
https://docs.python.org/3/library/index.html

seo company in mumbai 提到...

This blog is very helpful for students who want to learn.
here we provide an all assignment service to students.
python assignment help

Games world 提到...

Such a wonderful information blog post on this topic provides assignment service at affordable cost in a wide range of subject areas for all grade levels, we are already trusted by thousands of students who struggle to write their academic papers and also by those students who simply want Assignment helpto save their time and make life easypython assignment help