例如有以下模組
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()
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla22.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月我們用另一個程式引入 cla22.py
import cla22 as test a = test.SubDemo(12, 34) a.hello() a.bye() b = test.SubDemo(56, 78) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # http://pydoing.blogspot.com/ # 檔名:mod04.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月
執行結果如下

以上程式原本模組名稱為 cla22 ,我們利用 as ,引入 cla22 後將名稱改為 test ,因此程式內使用原本在 cla22 中的 SubDemo 就得接在 test 後面。
加入 from 就可以更簡化,例如
from cla22 import SubDemo as test a = test(12, 34) a.hello() a.bye() b = test(56, 78) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # http://pydoing.blogspot.com/ # 檔名: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 連用"
這邊打錯字了,已修改,感謝指正 ^_^
張貼留言