关于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
猜你喜欢
- SQLServer中建立与服务器的连接时出错的解决方案如下:步骤1:在SQLServer 实例上启用远程连接1.指向“开始->程序-&
- 目录实践步骤完整代码参考实践步骤1.寻找合适的Python库(安装是否麻烦、使用是否简便、执行会不会太久)moviepy 音视频库。分析需要
- innewDropList = [9,10,11,12,22,50,51,60,61]newDB = newDB[newDB['gr
- ASP+XML制作菜单管理!menu.asp 这个是前台执行部分<% '----------------
- 本文实例讲述了python实现矩阵乘法的方法。分享给大家供大家参考。具体实现方法如下:def matrixMul(A, B):
- 一、CONCAT函数concat函数是将多个字段或字符串拼接为一个字符串;但是字符串之间没有任何分隔。concat函数官方介绍-- CONC
- 本文实例讲述了python实现图片变亮或者变暗的方法。分享给大家供大家参考。具体实现方法如下:import Image# open an i
- 本文实例讲述了Python模块相关知识点。分享给大家供大家参考,具体如下:1.模块:定义:用来从逻辑上组织python代码(变量,函数,类,
- 1、PHP 中如何正确统计中文字数?这个是困扰我很久的问题,PHP 中有很多函数可以计算字符串的长度,比如下面的例子,分别使用了
- 已解决selenium模块利用performance获取network日志请求,抛出异常selenium.common.exceptions
- 点击进入Lombok官网下载Lombok jar包使用Lombok可能需要注意的地方(1)、当你的IDE是Idea时,要注意你的Idea是支
- 在这篇入门教程中,我们假定你已经有了PHP语言程序、MySQL数据库、计算机网络通讯及XML语言基础。如果你还没有,那么请先学习相关知识。我
- 今天有这样得一个需求,如果登陆人是客服的话,会查询订单是'该客服'以及还没有匹配客服的,刚开始想的是直接在sql语句上拼写&
- 前言copy()与deepcopy()之间的区分必须要涉及到python对于数据的存储方式。深复制被复制对象完全再复制一遍作为独立的新个体单
- SUBSTR函数是用来截取数据库某一列字段中的一部分。 在各个数据库的函数名称不一样(真是蛋疼,后发明的数据库难道不能同先发明的一样吗?)
- 在WEB开发中.我们可能都习惯使用下面的代码来获取客户端的IP地址: C#代码 //优先取得 * string IP = Request
- 1. Neovim是什么在此之前,我一直都是使用VSCODE或者WEB STORM编辑器的. 他们确实好用方便. 直到我得了腱鞘炎之后. 不
- 本文总结分析了Python装饰器简单用法。分享给大家供大家参考,具体如下:装饰器在python中扮演着很重要的作用,例如插入日志等,装饰器可
- 一、前言我打开4399小游戏网,点开了一个不知名的游戏,唔,做寿司的,有材料在一边,客人过来后说出他们的要求,你按照菜单做好端给他便好~要怎
- 流动网页设计有很多好处,但也只有在正确使用的时候。合适的技巧会使页面在大屏幕、小屏幕抑、PDA小屏幕上都能得到良好的呈现。但是,糟糕的代码结