python中main函数作用
在Python程序中,经常可以看到如下程序结构
def main():
# my code here
if __name__ == "__main__":
main()或者
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)为什么不是直接定义自己的函数,类似
def my_function()
# my code here
def my_function_two()
# my code here
# some code
# call function
# print(something)这是因为
如果不使用
main函数,代码就会在导入的时候作为一个模块直接运行其他语言(如C和Java)都有一个
main()函数在程序执行时调用,使用if结构,则更为熟悉定义了较为清晰和易读的代码
参考
Last updated
Was this helpful?