Python中if__name__=="__main__"详解

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

作为Python新手,常常会遇到 if __name__ == "__main__" 这个问题,下面我就来解释下它的作用。

比如你编写一个test.py文件,一个python文件就可以看作是一个python的模块,这个python模块(.py文件)有两种使用方式:直接运行使用和作为模块被其他模块调用。

解释下__name__:每一个模块都有一个内置属性__name__。而__name__的值取决与python模块(.py文件)的使用方式。如果是直接运行使用,那么这个模块的__name__值就是“__main__”;如果是作为模块被其他模块调用,那么这个模块(.py文件)的__name__值就是该模块(.py文件)的文件名,且不带路径和文件扩展名。

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

在该代码中,如果该文件直接运行,那么在后台中它会打印:“*****Direct execute*****”

如果是被其他模块所调用,那么在后台中它会打印:*****Module called*****

1#test.py文件23#!/usr/bin/python45frommathimportpi67defsquare(length):8area = length ** 29PRint"The area of square is %0.2f"%area1011defcube(length):12volume = length ** 313print"The volume of cube is %0.2f"%volume1415defcircle(radius):16area = pi * radius ** 217print"The area of circle is %0.2f"%area1819defsphere(radius):20volume = 4 * pi * radius ** 221print"The volume of sphere is %0.2f"%volume2223if__name__=="__main__":24try:25print"*****Direct execute*****"26num = float(raw_input("Enter a num:"))27square(num)28cube(num)29circle(num)30sphere(num)31exceptValueError, e:32print"Input a invaild num !"3334if__name__=="test":35try:36print"*****Module called*****"37num = float(raw_input("Enter a num:"))38square(num)39cube(num)40circle(num)41sphere(num)42exceptValueError, e:43print"Input a invaild num !"

我们使用两种方法运行test.py文件:

第一种,直接运行test.py文件。

直接在linux终端中运行

[Feng@A005 ~]$ ./test.py*****Direct execute*****Enter a num:5The area of square is25.00The volume of cube is125.00The area of circle is78.54The volume of sphere is314.16

可以看出,在linux终端中,它打印出了“*****Direct execute*****”,证明直接运行该模块(.py文件),该模块的__name__值就是“__main__”。

第二种,被其他模块调用。

进入python环境中,import test文件模块。

[Feng@A005 ~]$ python

Python2.6.6(r266:84292, Jul102013,22:48:45)

[GCC4.4.720120313(Red Hat4.4.7-3)] on linux2

Type"help","copyright","credits"or"license"formoreinformation.>>>import test*****Module called*****Enter a num:5The area of square is25.00The volume of cube is125.00The area of circle is78.54The volume of sphere is314.16

可以看出,在linux终端中,它打印除了“*****Module called*****”,证明是被其他模块调用了该模块(.py文件),该模块的__name__值就是该模块的文件名,且不带路径和文件扩展名。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航