例如有以下模組
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 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) if __name__ = = "__main__" : a = SubDemo( 12 , 34 ) a.hello() a.bye() b = SubDemo( 56 , 78 ) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # 檔名:cla22.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
我們用另一個程式引入 cla22.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import cla22 as test a = test.SubDemo( 12 , 34 ) a.hello() a.bye() b = test.SubDemo( 56 , 78 ) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # 檔名:mod04.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

以上程式原本模組名稱為 cla22 ,我們利用 as ,引入 cla22 後將名稱改為 test ,因此程式內使用原本在 cla22 中的 SubDemo 就得接在 test 後面。
加入 from 就可以更簡化,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from cla22 import SubDemo as test a = test( 12 , 34 ) a.hello() a.bye() b = test( 56 , 78 ) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # 檔名:mod05.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

中英文術語對照 | |
---|---|
關鍵字 | keyword |
模組 | module |
參考資料
http://docs.python.org/py3k/tutorial/modules.html
http://docs.python.org/py3k/reference/simple_stmts.html
http://docs.python.org/py3k/tutorial/modules.html
http://docs.python.org/py3k/reference/simple_stmts.html
2 則留言:
最前面筆誤"可以和另一個關鍵字 from 連用"
為"可以和另一個關鍵字 as 連用"
這邊打錯字了,已修改,感謝指正 ^_^
張貼留言