Python 3.1 快速導覽 - 模組 __name__ 屬性

模組 (module) 有特殊的 __name__ 屬性,若是該模組直接被執行, __name__ 就會被設定成 "__main__" ,因此作為模組的 Python 檔案都應該加入額外 if 陳述 (statement) ,如下

if __name__ == "__main__":
    #模組中可執行的程式碼


例如下面的 cla22.py 檔案
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 月


第 39 行到第 45 行
39
40
41
42
43
44
45
if __name__ == "__main__":
    a = SubDemo(12, 34)
    a.hello()
    a.bye()
    b = SubDemo(56, 78)
    b.hello()
    b.bye()


亦即判斷 __name__ 是否等於 "__main__" 的所在之處,若是相等,也就是 cla22.py 直接被執行, if 底下的程式碼就會被執行。


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






沒有留言: