Python中if __name__ == "__main__"详解


作为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文件
 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" %area
10 
11 def cube(length):
12     volume = length ** 3
13     print "The volume of cube is %0.2f" %volume
14 
15 def circle(radius):
16     area = pi * radius ** 2
17     print "The area of circle is %0.2f" %area
18 
19 def sphere(radius):
20     volume = 4 * pi * radius ** 2
21     print "The volume of sphere is %0.2f" %volume
22 
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:5
The area of square is 25.00
The volume of cube is 125.00
The area of circle is 78.54
The volume of sphere is 314.16
复制代码
可以看出,在linux终端中,它打印出了“*****Direct execute*****”,证明直接运行该模块(.py文件),该模块的__name__值就是“__main__”。
 
 
 
第二种,被其他模块调用。
 
    进入python环境中,import test文件模块。
 
复制代码
[Feng@A005 ~]$ python
Python 2.6.6 (r266:84292, Jul 10 2013, 22:48:45) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
*****Module called*****
Enter a num:5
The area of square is 25.00
The volume of cube is 125.00
The area of circle is 78.54
The volume of sphere is 314.16
复制代码
可以看出,在linux终端中,它打印除了“*****Module called*****”,证明是被其他模块调用了该模块(.py文件),该模块的__name__值就是该模块的文件名,且不带路径和文件扩展名。

相关内容

    暂无相关文章

评论关闭