为什么在if'

编程入门 行业动态 更新时间:2024-10-28 01:16:14
本文介绍了为什么在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'

本文发布于:2023-06-06 05:56:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/534760.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!