Python程序入口

连接

在一个.py文件中,如果不是在定义函数,也就是说不是在def关键字的内嵌结构内,python会默认其余部分函数是main函数,并自动执行,但正规工程中,一般都会将main函数写为:if__name__==__main__
每个人都在写,但很少有人问,其实这个用法很巧妙!

1

2

3

4

5

6

7

8

<code>#hello.py

def sayHello():

    str="hello"

    print(str);

if __name__ == "__main__":

    print ('This is main of module "hello.py"')

    sayHello()</code>

单独执行

当单独执行该module时,比如单独执行以上hello.py: python hello.py,则输出

?

1

2

<code>This is main of module "hello.py"

hello</code>

可以理解为”if name==”main“:” 这一句与c中的main()函数所表述的是一致的,即作为入口

猜你喜欢

转载自blog.csdn.net/weixin_40849273/article/details/82668117