zoukankan      html  css  js  c++  java
  • Python中if __name__ == '__main__' 的作用和原理

    参考网址:http://mp.weixin.qq.com/s/kxxhOQ7KB_VMwWeUENX7OQ

    t1.py:

    print('Loving Python')
    
    def main():
        print('Loving Python')
    #print (__name__)
    if __name__ == '__main__': main() print('Loving Python more')

    result:

    Loving Python
    #__main__ Loving Python Loving Python more

    t2.py

    import testindex.t1

    result:

    Loving Python
    #testindex.t1

    从上面我们可以看出,t2.py中只是执行了t1中的第一行,if __name__ == '__main__': 后面的数据都未执行

    t1.py:

    print('Loving Python')
    
    def main():
        print('Loving Python')
    print (__name__) if __name__ == '__main__': main() print('Loving Python more')

    result:

    Loving Python
    __main__ Loving Python Loving Python more

    t2.py

    import testindex.t1

    result:

    Loving Python
    testindex.t1

    然后我们在t1.py中添加print (__name__),在t1.py中结果为__main__,在t2.py中结果为testindex.t1

    再仔细想想,其运行原理也就是:

    由于每个python模块(python文件)都包含内置的变量__name__,当运行模块被执行的时候,__name__等于文件名(包含了后缀.py)。如果import到其他模块中,则__name__等于模块名称(不包含后缀.py)。而“__main__”等于当前执行文件的名称(包含了后缀.py)。所以当模块被直接执行时,__name__ == '__main__'结果为真;而当模块被import到其他模块中时,__name__ == '__main__'结果为假,就是不调用对应的方法。

    简而言之就是:__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ 。当模块被直接运行时,代码将被运行,当模块是被导入时,代码不被运行。

  • 相关阅读:
    kubernetes获取Pod内容器信息
    etcd空间配额2G限制优化
    kubernetes集群之GC处理
    kubernetes之statefulset控制器介绍
    基于MySQL Binlog的Elasticsearch数据同步实践
    Nacos
    Python最佳工程实践,建立一个完美的工程项目
    图数据库的内部结构 (NEO4j)
    5个用/不用GraphQL的理由
    Neo4J 查找两节点之间的路径
  • 原文地址:https://www.cnblogs.com/fireporsche/p/8529458.html
Copyright © 2011-2022 走看看