顾睐 发表于 2023-1-6 16:21:40

Python中的main方法教程

估计很多人跟我一样初学python看代码的时候先找一下main()方法,从main往下看。但事实上python中是没有你理解中的“main()”方法的。
言归正传
if name == "main":可以看成是python程序的入口,就像java中的main()方法,但不完全正确。
事实上python程序是从上而下逐行运行的,在.py文件中,除了def后定义函数外的代码都会被认为是“main”方法中的内容从上而下执行。如果只是写个伟大的"hello world",不想写函数的话,仅仅是print('hello world')就可以,这就是一个“程序”,不需要所谓的“main”方法入口。当然如果是测试函数功能就需要在.py文件中写上if name == "main",再调用函数。
比如如下hello.py文件:
# Python学习交流QQ群:711312441
print("first")


def sayHello():
    str = "hello"
    print(str);
    print(__name__+'from hello.sayhello()')


if __name__ == "__main__":
    print ('This is main of module "hello.py"')
    sayHello()
    print(__name__+'from hello.main')运行结果:
first
This is main of module "hello.py"
hello
__main__ from hello.sayhello()
__main__ from hello.main懂我意思吧?先执行的第一行print再执行“入口”中的东西
话说回来,if name == "main"这句话是个什么意思呢?
name__其实是一个内置属性,指示当前py文件调用方式的方法。当上述例子运行的时候,整个程序中不管是哪个位置的__name__属性,值都是__main,当这个hello.py文件作为模块被导入到另一个.py文件中(即import)比如说world.py,并且你运行的是world.py,此时hello.py中的__name__属性就会变成hello,所谓的入口因为if判断失败就不执行了
所以if语句的判断成功虚拟了一个main()方法。
说到了phthon是逐行执行的,所以当它读到import hello的时候,也会执行hello.py,比如运行如下world.py文件:
import hello#上一个例子的hello.py

if __name__ == "__main__":
    print ('This is main of module "world.py"')
    hello.sayHello()
    print(__name__)执行结果:
first
This is main of module "world.py"
hello
hellofrom hello.sayhello()
main可以看到hello.py中的第一行print('first')直接被执行了,并且hello.py中的__name__输出的也是hello,world.py中的name输出的是__main__
总结:
要适应python没有main()方法的特点。所谓的入口其实也就是个if条件语句,判断成功就执行一些代码,失败就跳过。没有java等其他语言中那样会有特定的内置函数去识别main()方法入口,在main()方法中从上而下执行

来源:https://www.cnblogs.com/xxpythonxx/p/17031000.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Python中的main方法教程