简体   繁体   English

Python __name __()主要功能

[英]Python __name__() main function

I have tried looking for an answer online but couldn't find it. 我尝试过在网上寻找答案,但找不到。 I am fairly new to python and wondering if you could have multiple main function in a program. 我是python的新手,想知道您是否可以在程序中具有多个主要功能。 For example: 例如:

ask_user = int(input('enter your choice (1 or 2): '))

if ask_user == 1:
    def print_hello():
        print('hello world')
    def main():
        print_hello()

    if __name__ == '__main__': main()

elif ask_user == 2:
    def print_hi():
        print('hi')
    def main():
        print_hi()

    if __name__ == '__main__': main()

Is this a good programing practice? 这是好的编程习惯吗?

This wouldn't be considered good programming practice, no. 不,这不会被视为良好的编程习惯。 Like index.html , the point of main() is to have a primary entry point to the program. index.html一样, main()的要点是具有程序的主要入口点。 Even if a particular language allowed that sort of thing, it would be confusing for anyone reading the code and trying to figure out where to start. 即使某种特定的语言允许这样做,对于任何阅读代码并试图从何处开始的人来说,这也将造成混乱。 For the display options, you would use separate functions with meaningful names, such as print_hello_world and print_hi , and they would both be able to be called by main() . 对于显示选项,您将使用具有有意义名称的单独函数,例如print_hello_worldprint_hi ,它们都可以被main()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM