我已经看到一些代码示例和教程使用
def main():
# my code here
if __name__ == "__main__":
main()
但是为什么呢?是否有理由不在文件的顶部定义函数,然后在下面编写代码?即
def my_function()
# my code here
def my_function_two()
# my code here
# some code
# call function
# print(something)
我只是想知道是否有什么押韵的?
其他人都已经回答了,但我想我还有一些东西要补充。
if语句调用main()的原因(顺序不分先后):
Other languages (like C and Java) have a main() function that is called when the program is executed. Using this if, we can make Python behave like them, which feels more familiar for many people.
Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)
It will be possible to import that python code as a module without nasty side-effects.
This means it will be possible to run tests against that code.
This means we can import that code into an interactive python shell and test/debug/run it.
Variables inside def main are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.
但是,您不需要编写main()函数并在if语句中调用它。
我自己通常开始编写没有任何函数的小脚本。如果脚本变得足够大,或者如果我觉得把所有代码都放在一个函数中会对我有好处,那么我就会重构代码并执行它。在编写bash脚本时也会发生这种情况。
即使您将代码放在主函数中,也不需要完全按照这种方式编写。一个简洁的变体可以是:
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)
这意味着您可以从传递自定义参数的其他脚本(或交互式shell)调用main()。这在单元测试或批处理中可能很有用。但是请记住,上面的代码将需要解析argv,因此使用传递已解析参数的不同调用可能会更好。
在我写的一个面向对象的应用程序中,代码是这样的:
class MyApplication(something):
# My code here
if __name__ == "__main__":
app = MyApplication()
app.run()
因此,请随意编写更适合您的代码。:)
其他人都已经回答了,但我想我还有一些东西要补充。
if语句调用main()的原因(顺序不分先后):
Other languages (like C and Java) have a main() function that is called when the program is executed. Using this if, we can make Python behave like them, which feels more familiar for many people.
Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)
It will be possible to import that python code as a module without nasty side-effects.
This means it will be possible to run tests against that code.
This means we can import that code into an interactive python shell and test/debug/run it.
Variables inside def main are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.
但是,您不需要编写main()函数并在if语句中调用它。
我自己通常开始编写没有任何函数的小脚本。如果脚本变得足够大,或者如果我觉得把所有代码都放在一个函数中会对我有好处,那么我就会重构代码并执行它。在编写bash脚本时也会发生这种情况。
即使您将代码放在主函数中,也不需要完全按照这种方式编写。一个简洁的变体可以是:
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)
这意味着您可以从传递自定义参数的其他脚本(或交互式shell)调用main()。这在单元测试或批处理中可能很有用。但是请记住,上面的代码将需要解析argv,因此使用传递已解析参数的不同调用可能会更好。
在我写的一个面向对象的应用程序中,代码是这样的:
class MyApplication(something):
# My code here
if __name__ == "__main__":
app = MyApplication()
app.run()
因此,请随意编写更适合您的代码。:)