模块中的函数首先执行,即使在函数调用之前将其放置后也没有执行打印语句

发布于 2025-02-07 02:36:00 字数 713 浏览 0 评论 0原文

我是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:
enter image description here

Now in my main.py file I have imported models module
from models.eq_melting import * from models.frac_melting import *. After that I put some print statements :
enter image description here

Now the problem is whatever function that is residing in files of module models, is getting executed first rather than the print statements.
enter image description here

Please help me to understand why this is happening.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

王权女流氓 2025-02-14 02:36:00

导入模块时,您实际上正在执行它,因此模块中的每个语句都会运行。如果只是函数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 defs then you will just add those functions to the namespace, but not actually run the code they contain. However if it contains print 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 the if condition won't be satisfied, but if the module is executed directly as a script then the if 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文