python程序执行顺序

在C/C++/Java中,main是程序执行的起点,Python中,也有类似的运行机制,但方式却截然不同:Python使用缩进对齐组织代码的执行,所有没有缩进的代码(非函数定义和类定义),都会在载入时自动执行,这些代码,可以认为是Python的main函数。
hello.py
def foo():
    str="function"
    print(str);
if __name__=="__main__":
    print("main")
    foo()

其中if name==”main“:这个程序块类似与Java和C语言的中main(主)函数
在Cmd中运行结果
C:\work\python\divepy>python hello.py
main
function
在Python Shell中运行结果
import hello
hello.foo()
function
hello.name
‘hello’
可以发现这个内置属性name自动的发生了变化。
这是由于当你以单个文件运行时,name便是main
当你以模块导入使用时,这个属性便是这个模块的名字。

猜你喜欢

转载自blog.csdn.net/qq_30614451/article/details/82049675