为什么在if'__main__'内部未定义main()函数? [英] Why is the main() function not defined inside the if '__main__'?

查看:157
本文介绍了为什么在if'__main__'内部未定义main()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您经常会看到这种情况(变化a):

You can often see this (variation a):

def main():
   do_something()
   do_sth_else()

if __name__ == '__main__':
    main()

我现在想知道为什么不是这个(变化b):

And I am now wondering why not this (variation b):

if __name__ == '__main__':
   do_something()
   do_sth_else()

至少此(变体c):

if __name__ == '__main__':
    def main():
        do_something()
        do_sth_else()

    main()

当然,main()中的函数调用可能不是函数调用,它们只是表示您可能要在main()函数中执行的任何操作.

Of course the function calls inside main() might not be function calls, they just represent anything you might want to do in your main() function.

那么为什么人们比其他人更喜欢变异a?仅仅是风格/感觉还是有一些真正的原因?如有可能,请同时链接来源.

So why do people prefer variation a over the others? Is it just style/feeling or are there some real reasons? If possible, please also link sources.

推荐答案

为什么将main()函数限制为仅使用命令行?

Why limit your main() function to command line usage only?

通过在模块范围内定义main()函数,您现在可以包装脚本并更改其调用方式.也许您想在sys.argv中设置默认参数,也许您想在另一个脚本中重用代码.

By defining a main() function at module scope, you can now wrap your script and alter how it is called. Perhaps you want to set default arguments in sys.argv, perhaps you want to reuse the code in another script.

这篇关于为什么在if'__main__'内部未定义main()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆