关于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
投稿

猜你喜欢

  • 在keras 中获取张量 tensor 的维度大小实例

    2023-08-27 21:58:12
  • pycharm利用pyspark远程连接spark集群的实现

    2023-10-08 06:49:00
  • 纯JS实现动态时间显示代码

    2024-05-02 17:31:34
  • python和java哪个学起来更简单

    2023-06-11 22:49:59
  • MySQL数据库与表的最基本命令大盘点

    2010-08-31 14:29:00
  • python使用PIL实现多张图片垂直合并

    2023-10-28 12:19:45
  • Golang中struct{}和struct{}{}的区别解析

    2024-04-23 09:36:21
  • Python对列表中的各项进行关联详解

    2023-10-26 20:19:34
  • 银行账号输入格式化, 支持部分浏缆器

    2007-09-26 18:27:00
  • Golang二维切片初始化的实现

    2024-05-09 14:57:54
  • Div+CSS+JS树型菜单,可刷新

    2024-04-17 09:52:18
  • 全面剖析Python的Django框架中的项目部署技巧第1/2页

    2021-09-24 23:46:58
  • python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】

    2023-07-09 01:15:42
  • python使用socket实现图像传输功能

    2023-08-30 17:10:17
  • Python多进程分块读取超大文件的方法

    2023-12-07 02:19:28
  • 详解vue数组遍历方法forEach和map的原理解析和实际应用

    2024-05-05 09:06:18
  • Python真题案例之错位键盘 单词长度 字母重排详解

    2023-03-18 02:57:26
  • 一文详解Python中多进程和进程池的使用方法

    2023-12-01 04:10:12
  • Python实现上下文管理器的方法

    2021-06-22 17:31:15
  • 基于JavaScript实现回到页面顶部动画代码

    2024-05-25 15:17:28
  • asp之家 网络编程 m.aspxhome.com