国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Python中if__name__=="__main__"詳解

2019-11-14 17:39:53
字體:
來源:轉載
供稿:網友

作為Python新手,常常會遇到 if __name__ == "__main__" 這個問題,下面我就來解釋下它的作用。

比如你編寫一個test.py文件,一個python文件就可以看作是一個python的模塊,這個python模塊(.py文件)有兩種使用方式:直接運行使用和作為模塊被其他模塊調用。

解釋下__name__:每一個模塊都有一個內置屬性__name__。而__name__的值取決與python模塊(.py文件)的使用方式。如果是直接運行使用,那么這個模塊的__name__值就是“__main__”;如果是作為模塊被其他模塊調用,那么這個模塊(.py文件)的__name__值就是該模塊(.py文件)的文件名,且不帶路徑和文件擴展名。

例如《Python核心編程》第二版第五章答案 中的5-8題。

在該代碼中,如果該文件直接運行,那么在后臺中它會打?。?ldquo;*****Direct execute*****

如果是被其他模塊所調用,那么在后臺中它會打?。?span style="color: #800000;">*****Module called*****

 1 #test.py文件 2  3 #!/usr/bin/python 4  5 from math import pi 6  7 def square(length): 8     area = length ** 2 9     PRint "The area of square is %0.2f" %area10 11 def cube(length):12     volume = length ** 313     print "The volume of cube is %0.2f" %volume14 15 def circle(radius):16     area = pi * radius ** 217     print "The area of circle is %0.2f" %area18 19 def sphere(radius):20     volume = 4 * pi * radius ** 221     print "The volume of sphere is %0.2f" %volume22 23 if __name__ == "__main__":24     try:25         print "*****Direct execute*****"26         num = float(raw_input("Enter a num:"))27         square(num)28         cube(num)29         circle(num)30         sphere(num)31     except ValueError, e:32         print " Input a invaild num !"33 34 if __name__ == "test":35     try:36         print "*****Module called*****"37         num = float(raw_input("Enter a num:"))38         square(num)39         cube(num)40         circle(num)41         sphere(num)42     except ValueError, e:43         print " Input a invaild num !"

我們使用兩種方法運行test.py文件:

第一種,直接運行test.py文件。

    直接在linux終端中運行    

[Feng@A005 ~]$ ./test.py *****Direct execute*****Enter a num:5The area of square is 25.00The volume of cube is 125.00The area of circle is 78.54The volume of sphere is 314.16

可以看出,在linux終端中,它打印出了“*****Direct execute*****”,證明直接運行該模塊(.py文件),該模塊的__name__值就是“__main__”。

 

第二種,被其他模塊調用。

    進入python環境中,import test文件模塊。

[Feng@A005 ~]$ pythonPython 2.6.6 (r266:84292, Jul 10 2013, 22:48:45) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import test*****Module called*****Enter a num:5The area of square is 25.00The volume of cube is 125.00The area of circle is 78.54The volume of sphere is 314.16

可以看出,在linux終端中,它打印除了“*****Module called*****”,證明是被其他模塊調用了該模塊(.py文件),該模塊的__name__值就是該模塊的文件名,且不帶路徑和文件擴展名。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大丰市| 门头沟区| 灵石县| 池州市| 龙川县| 屯门区| 洪雅县| 平舆县| 黄梅县| 太仓市| 桃江县| 龙门县| 英德市| 闽清县| 大城县| 天水市| 寻甸| 隆安县| 正镶白旗| 甘洛县| 高平市| 武陟县| 太仆寺旗| 玉环县| 衡南县| 根河市| 高邮市| 岳西县| 滨州市| 天峨县| 顺昌县| 平阳县| 通化市| 荃湾区| 寻乌县| 新河县| 辉南县| 历史| 清涧县| 沙雅县| 阿坝县|