python:我需要更好地理解导入和包

发布于 2024-11-29 01:41:35 字数 1194 浏览 4 评论 0原文

我的应用程序具有与此类似的结构:

myapp.py
basemod.py
[pkg1]
    __init__.py
    mod1.py
[pkg2]
    __init__.py
    mod2.py

myapp.py:

import pkg1
import pkg2

if __name__ == '__main__':
    pkg1.main()
    pkg2.main()

basemod.py:

import pkg1


def get_msg():
    return pkg1.msg

pkg1/__init__.py:

import mod1

msg = None


def main():
    global msg
    mod1.set_bar()
    msg = mod1.bar

pkg1/ mod1.py:

bar = None


def set_bar():
    global bar
    bar = 'Hello World'

pkg2/__init__.py:

import mod2


def main():
    mod2.print_foo()

pkg2/mod2.py:

import basemod

foo = basemod.get_msg()


def print_foo():
    print(foo)

如果我运行 myapp.py 我得到:

None

虽然在我心里我会期望:

Hello World

我的目标是让两个包完全独立,并且仅通过 basemod.py 进行通信,这是 pkg1 的一种 API。
我开始认为我还没有完全理解包之间的导入是如何工作的,我做错了什么?

谢谢你!

My application has a structure similar to this one:

myapp.py
basemod.py
[pkg1]
    __init__.py
    mod1.py
[pkg2]
    __init__.py
    mod2.py

myapp.py:

import pkg1
import pkg2

if __name__ == '__main__':
    pkg1.main()
    pkg2.main()

basemod.py:

import pkg1


def get_msg():
    return pkg1.msg

pkg1/__init__.py:

import mod1

msg = None


def main():
    global msg
    mod1.set_bar()
    msg = mod1.bar

pkg1/mod1.py:

bar = None


def set_bar():
    global bar
    bar = 'Hello World'

pkg2/__init__.py:

import mod2


def main():
    mod2.print_foo()

pkg2/mod2.py:

import basemod

foo = basemod.get_msg()


def print_foo():
    print(foo)

If I run myapp.py I get:

None

While in my mind I'd expect:

Hello World

My goal is to keep the two packages completely independent from each other, and only communicating through basemod.py, which is a sort of API to pkg1.
I'm starting to think that I have not completely understood how imports among packages work, what am I doing wrong?

Thank you!

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

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

发布评论

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

评论(1

北城挽邺 2024-12-06 01:41:35

我花了一些时间阅读所有代码,但看起来你的问题出在 pkg2/mod2.py 中。行 foo = basemod.get_msg() 在第一次导入该文件时执行,并且不再执行。因此,当您更改 mod1.bar 的值时,它已经执行,并且 fooNone

解决方案应该只是将该行移动到 print_foo 函数中,因此它仅在调用该函数时执行 - 即在设置相关值的代码之后。

Took me a while to read through all that code, but it looks like your problem is in pkg2/mod2.py. The line foo = basemod.get_msg() is executed the first time that file is imported, and never again. So by the time you change the value of mod1.bar, this has already executed, and foo is None.

The solution should simply be to move that line into the print_foo function, so it is only executed when that function is called - which is after the code that sets the relevant value.

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