python中if __name__ == '__main__' :main(()

例如:

if __name__ == '__main__':
    main()

如果运行的是主函数的话,执行下一句main()

如果作为模块被其他文件导入使用的话,我们就不执行后面的main()什么的。

 

看个例子:

# test.py
def main():
    print('Hello, world!')
main()

这是一个打印 Hello,world! 的简单程序

我们尝试从其他文件调用它:

# test1.py
import test

test.main()

运行test1.py,出现打印了两个Hello,word!

①Hello,world!来自于test.py中的main(),

②Hello,world!来自于test1.py中的test.main(),造成最后输出两个Hello,world!

本来只想调用test里面的main函数打印一次Hello,world!,可是这里却打印了两次,违背了我们的本意

想让test1.py只输出一个Hello,world!的话,我们可以在test.py中去掉最后一行运行的main(),但是这会使test.py运行的时候什么也不打印

这里我们既想让test.py运行输出结果,又想调用的时候不重复,就需要使用if __name__ == '__main__'

修改之后的test.py:

# test.py
def main():
    print('Hello, world!')

if __name__=='__main__':
    main()

这样,就只在运行test.py的时候会打印这个Hello,world!

但我们在运行test1.py的时候,if __name__ == '__main__'这个语句就不成立,那么test.py中的Hello,world!就不会打印

只会打印test1中的Hello,world!

原文地址:https://www.cnblogs.com/chen8023miss/p/11189938.html