模块中的函数首先执行,即使在函数调用之前将其放置后也没有执行打印语句
我是Python的新手,并尝试了自己的宠物项目。因此,我的项目目录看起来像这样:
现在在我的 main.py 文件中 来自Models.eq_melting Import *从Models.frac_melting导入 *
。之后,我放了一些印刷语句:
现在问题是在模块模型文件中驻留的任何功能,首先被执行而不是打印语句。
请帮助我了解为什么会发生这种情况。
I am new to python and trying out my own pet project. So, my project directories look like this:
Now in my main.py file I have imported models modulefrom models.eq_melting import * from models.frac_melting import *
. After that I put some print statements :
Now the problem is whatever function that is residing in files of module models, is getting executed first rather than the print statements.
Please help me to understand why this is happening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
导入模块时,您实际上正在执行它,因此模块中的每个语句都会运行。如果只是函数
def
s,则您只需将这些功能添加到名称空间,但实际上不运行它们所包含的代码。但是,如果它包含print
或其他语句,则将执行它们。要总结当您导入模块时,请执行该模块中的所有内容。
这也是为什么您经常看到的代码看起来像
如果__name __ ==“ __ main __”
在许多模块的底部。如果未满足条件,则导入,但是如果将模块直接作为脚本执行。
附带说明,您应该尽力避免
从模块导入 *
- 它将使调试更加困难,因为它使计算机(和人类)不可能知道其名称中的项目在哪里空间来自。When you import a module you are in fact executing it, so every statement in the module will get run. If it is just function
def
s then you will just add those functions to the namespace, but not actually run the code they contain. However if it containsprint
or other statements then they will get executed.To summarise when you import a module you execute everything in that module.
This is also why you see very often code that looks like
if __name__ == "__main__"
at the bottom of many modules. If the module gets imported theif
condition won't be satisfied, but if the module is executed directly as a script then theif
condition will be satisfied and the code will run.As a side note you should do your best to avoid
from module import *
- it will make debugging ten times harder as it makes it impossible for the computer (and the human) to know where items in its name space came from.