zoukankan      html  css  js  c++  java
  • Python main 函数

    Python 中 main 语句的作用整理:

    1、Python 语句中可以不包含主函数 main 函数;

    2、if __name__=='__main__' 语句是为了自我调试代码方便,作为执行程序的入口,在 Python 脚本作为 module 被 import 时该语句下代码不运行;

    下面编写两个测试代码:print_test.pyprint_test_module.dy

    print_test.py (这里的 main 部分可以没有)如下:

     1 import datetime
     2 print('Hello World')
     3 print('Time is',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
     4 print('__name__ value: ', __name__) 
     5 
     6 def main():
     7     print('This is main function')
     8     
     9 if __name__=='__main__':
    10     #main()
    11     print('HaHa')
    12    

    print_test_module.py 如下:

    1 import print_test
    2 print('将print_test.py作为module导入执行')

    单独运行 print_test.py 时,结果如下:

    1 Hello World
    2 Time is 2021-08-24 15:48:54
    3 __name__ value:  __main__
    4 HaHa

    单独运行 prin_test_module.py 时,结果如下:

    1 Hello World
    2 Time is 2021-08-24 15:53:48
    3 __name__ value:  print_test
    4 将print_test.py作为module导入执行

    对比两段程序运行结果可发现,当直接运行包含 main 函数的程序时,main 函数会被执行,同时程序的__name__变量值为'__main__'。

    当包含有 main 函数的程序 print_test.py 被作为 module 被 import 时,print_test_module.py 对应的__name__变量值为该 module 对应的函数名称 print_test,因此 print_test.py 中的 main 函数不会被执行。

    若想在 print_test_module.py 中也执行 main 函数,则需要添加语句:print_test.main(),即

     1 import print_test
     2 print('将print_test.py作为module导入执行')
     3 print_test.main()
     4 
     5 结果:
     6 Hello World
     7 Time is 2021-08-24 15:56:59
     8 __name__ value:  print_test
     9 将print_test.py作为module导入执行
    10 This is main function

    可以看到,main 函数就执行了。

  • 相关阅读:
    SEO之关键词选择
    我所了解的搜索引擎工作原理
    搜索引擎工作原理
    SEO定义目的,优化的好处
    今天开始我的博客旅程啦!
    [ABC209E] Shiritori
    Codeforces Global Round 12
    CF771E Bear and Rectangle Strips
    CF1392H ZS Shuffles Cards
    CF1439D INOI Final Contests
  • 原文地址:https://www.cnblogs.com/lmj-sky/p/15180751.html
Copyright © 2011-2022 走看看