首页 > 编程知识 正文

python方法调用,python中main函数使用

时间:2023-05-05 01:33:47 阅读:32745 作者:704

我想很多人和我一样第一次看python代码的时候,会先找main ()方法,从main往下看。 但是,实际上python没有你理解的“main ()”方法。 言归正传

if name=='main':可以被认为是java的main (就像方法一样,是python程序的入口,但不完全正确。 实际上,python程序从上到下一行一行地运行。 在. py文件中,除了在def之后定义函数之外,其他代码都假定" main "方法的内容从上到下执行。 如果你只是写伟大的“hello world”,而不想写函数,你只需要打印(“hello world”)。 这就是“程序”,不需要所谓的“主”方法的入口。 当然,如果要测试函数功能,必须在. py文件中写if name=='main ',然后调用函数。 例如,以下hello.py文件:

打印(第一个) ) ) )。

def sayHello () :

str='hello '

打印(str;

print (_ name _ _ ' from hello.say hello () ) )

if __name__=='__main__':

打印(thisismainofmodule ' hello.py ' ) )。

sayHello () ) )。

print(__name__ 'from hello.main ' )

执行结果:

第一个

This is main of module 'hello.py '

你好

__main__ from hello.sayhello (

__main__ from hello.main

你明白意思吧? 首先运行第一行的print,然后运行“入口”中的内容。 顺便问一下,if name=='main '这个词是什么意思? name__是一个内置属性,指示如何调用当前py文件。 当执行上述示例时,在整个程序中,无论是哪个位置的__name__属性,值都是__main,其中hello.py文件作为模块是另一个. py文件,例如world.py 由于运行的是import ph thon,它逐行运行,因此当您阅读import hello时,它也会运行hello.py,例如运行以下world.py文件:

import hello#上一个示例中的hello.py

if __name__=='__main__':

打印(thisismainofmodule ' world.py ' ) )。

hello.sayHello () ) )

print(__name__ )

执行结果: ` ` ` firstthisismainofmodule ' world.py ' hellohellofromhello.say hello () ) main

hello.py第一行的print('first ' )直接运行,hello.py的__name__输出hello,world.py的name输出__main__

*总结:请应对python没有main ()方法的特点。 入口其实是if条件语句,判断成功后执行几个代码,失败后跳过。 与其他语言(如java )一样,它识别main ) )方法的条目,main ) )方法没有自上而下执行的特定内置函数

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。