【问题标题】:Why Python module execute only first time codes which are outside function/class code为什么 Python 模块只执行函数/类代码之外的第一次代码
【发布时间】:2019-12-14 10:35:04
【问题描述】:

文件words.py

def print_word():
    print("Hello Words")

print(__name__) 

当我从控制台运行上面的代码时:

(base) C:\Users\Desktop\Python>python words.py
__main__

(base) C:\Users\Desktop\Python>python words.py
__main__

(base) C:\Users\Desktop\Python>python words.py
__main__

(base) C:\Users\Desktop\Python>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from words import *
words
>>> from words import *
>>>

为什么在导入过程中它只执行一次打印,但在运行 python words.py 时它执行打印的次数与我们执行的次数一样多?

【问题讨论】:

    标签: python-3.x import module


    【解决方案1】:

    当您导入一个模块时,Python 会创建该模块的一个模块实例。

    在第一次导入后,解释器已经有了该模块的实例,因此它不执行任何操作

    Python 的导入文档:documentation

    第一次导入模块时,Python 会搜索该模块,如果找到,它会创建一个模块对象并对其进行初始化。

    您可以阅读更多关于模块的加载过程here

    • 如果在 sys.modules 中存在具有给定名称的模块对象,import 将已经返回它。

    • 在加载器执行模块代码之前,该模块将存在于 sys.modules 中。这是至关重要的,因为模块代码可能(直接或间接)导入自身;预先将其添加到 sys.modules 可以防止最坏情况下的无限递归和最佳情况下的多次加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多