初次接触Python的人会很不习惯Python没有main主函数。
这里简单的介绍一下,在Python中使用main函数的方法
#hello.py
def foo():
str="function"
print(str);
if __name__=="__main__":
print("main")
foo()
其中if __name__=="__main__":这个程序块类似与Java和C语言的中main(主)函数
在 terminal 中运行结果:
sina@sina-virtual-machine:~$ python hello.py
main
function
在Python Shell中运行结果
sina@sina-virtual-machine:~$ python
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
>>> hello.foo()
function
>>> hello.__name__
'hello'
可以发现这个内置属性__name__自动的发生了变化。 这是由于当你以单个文件运行时,__name__ 便是 __main__ 当你以模块导入使用时,这个属性便是这个模块的名字。
在C/C++/Java中,main是程序执行的起点,Python中,也有类似的运行机制,但方式却截然不同:Python使用缩进对齐组织代码的执行,所有没有缩进的代码(非函数定义和类定义),都会在载入时自动执行,这些代码,可以认为是Python的main函数。
每个文件(模块)都可以任意写一些没有缩进的代码,并且在载入时自动执行,为了区分主执行文件还是被调用的文件,Python引入了一个变量__name__,当文件是被调用时,__name__的值为模块名,当文件被执行时,__name__为'__main__'。这个特性,为测试驱动开发提供了极好的支持,我们可以在每个模块中写上测试代码,这些测试代码仅当模块被Python直接执行时才会运行,代码和测试完美的结合在一起。