• Python学习笔记:__ name__ == '__ main __' 代表什么?


    经常在 .py 脚本文件中看到这么一句: if __name__ == '__main__': ,那么这句声明到底代表什么?又发挥着什么作用呢?

    一、介绍

    Python 程序不同于其他语言,文件自上而下执行。

    • 作用

    添加这段代码的作用是让该 Python 文件既可以独立运行,也可以当做模块导入到其他文件。

    当导入到其他的脚本文件的时候,此时 __name__ 的名字其实是导入模块的名字,不是 __main__,因此 main 中的代码便不会执行。

    • 实例测试

    新建一个测试文件 test_main.py 如下:

    def fun():
    	print("This is function.")
    
    if __name__ == '__main__':
    	fun()
    	print("This is main function.")
    
    ''''    
    C:> python test_main.py
    This is function.
    This is main function.
    '''
    

    test_main.py 作为模块导入,并执行测试。

    import os
    os.chdir(r"C:UsersHiderDesktop	est")
    
    import test_main as tm
    tm.fun()
    
    '''
    This is function.
    '''
    

    __main__ 模块中的代码并未执行。

    二、全局内置变量

    __name__ 存储当前py文件调用方法的方法名。

    # 直接运行
    def fun():
        print("This is function.")
        
    def print_name():
        print('__name__的值是:', __name__)
    
    if __name__ == '__main__':
        fun()
        print_name()
        print("This is main function.")
    '''
    This is function.
    __name__的值是: __main__
    This is main function.
    '''
    
    # 作为导入
    import os
    os.chdir(r"C:UsersHiderDesktop	est")
    
    import test_main as tm
    tm.fun()
    tm.print_name()
    '''
    This is function.
    __name__的值是: test_main
    '''
    

    参考链接1:Python中 '__main__' 模块的作用

    参考链接2:你常常在写的 if __name__ == '__main__' 到底是个啥?

  • 相关阅读:
    操作系统进程调度策略
    runnable & callable
    leetcode 124 二叉树中的最大路径和
    leetcode 24 两两交换链表中的节点
    leetcode 93 复原IP地址
    C++ 11 move
    leetcode 64 最小路径和
    leetcode 1143 最长公共子序列
    leetcode 528 按权重随机选择
    数据挖掘面试题(1)
  • 原文地址:https://www.cnblogs.com/hider/p/14788880.html
Copyright © 2020-2023  润新知