python:我需要更好地理解导入和包
我的应用程序具有与此类似的结构:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我花了一些时间阅读所有代码,但看起来你的问题出在 pkg2/mod2.py 中。行
foo = basemod.get_msg()
在第一次导入该文件时执行,并且不再执行。因此,当您更改mod1.bar
的值时,它已经执行,并且foo
为None
。解决方案应该只是将该行移动到 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 ofmod1.bar
, this has already executed, andfoo
isNone
.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.