关于Python中的main方法教程

作者:Python 时间:2021-12-30 08:31:37 

正文开始

if name == "main":可以看成是python程序的入口,就像java中的main()方法,但不完全正确。

事实上python程序是从上而下逐行运行的,在.py文件中,除了def后定义函数外的代码都会被认为是“main”方法中的内容从上而下执行。如果只是写个伟大的"hello world",不想写函数的话,仅仅是print(‘hello world’)就可以,这就是一个“程序”,不需要所谓的“main”方法入口。当然如果是测试函数功能就需要在.py文件中写上if name == "main",再调用函数。

比如如下hello.py文件:

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://blog.csdn.net/sinat_38682860/article/details/128581592

标签:Python,main,方法
0
投稿

猜你喜欢

  • ASP实现防止网站被采集代码

    2011-03-25 10:40:00
  • MySQL分区的功能和限制讲解

    2010-10-14 14:03:00
  • ASP中遍历和操作Application对象的集合

    2007-09-13 12:45:00
  • 扩展性很好的一个分页存储过程分享

    2011-11-03 17:04:16
  • Google谷歌的CSS前景图片合并技术

    2009-07-13 12:21:00
  • python模块常用用法实例详解

    2023-07-30 01:38:54
  • jQuery技巧

    2009-09-27 12:28:00
  • 网马解密大讲堂——网马解密中级篇(Freshow工具使用方法)

    2009-09-16 15:09:00
  • MySQL Dump/Restore

    2010-10-14 13:49:00
  • php实现mysql备份恢复分卷处理的方法

    2023-11-16 20:55:33
  • 破解空间实现域名绑定到子目录方法

    2010-03-14 11:29:00
  • 如何用表单在线建立目录?

    2010-06-16 09:49:00
  • X/HTML5 v.s. XHTML2(II)

    2008-06-18 13:19:00
  • 安装MySQL的步骤和方法

    2009-07-30 08:38:00
  • ASP编程入门进阶教程

    2008-06-29 18:00:00
  • 在ASP.NET 2.0中操作数据之三十九:在DataList的编辑界面里添加验证控件

    2023-07-06 02:02:48
  • SQL Server端口更改后的数据库连接方式

    2008-12-29 14:11:00
  • 用正则替换所有URL

    2009-03-13 13:51:00
  • PHP设计模式之观察者模式浅析

    2023-05-27 12:20:11
  • 配置SQL Server文件组对应不同的RAID系统

    2009-01-04 14:31:00
  • asp之家 网络编程 m.aspxhome.com