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 | from cla22 import * a = SubDemo( 12 , 34 ) a.hello() a.bye() b = SubDemo( 56 , 78 ) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # 檔名:mod02.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

星號表示所有的內容,如果不寫星號,就得把 SubDemo 寫出來,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from cla22 import SubDemo a = SubDemo( 12 , 34 ) a.hello() a.bye() b = SubDemo( 56 , 78 ) b.hello() b.bye() # 《程式語言教學誌》的範例程式 # 檔名:mod03.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

我們可以看到兩者的執行結果是一樣的,如果需要引入的名稱很多,星號可以省下許多打字的時間。
中英文術語對照 | |
---|---|
模組 | module |
關鍵字 | keyword |
陳述 | statement |
屬性 | attribute |
參考資料
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
沒有留言:
張貼留言