加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 从子包或全路径差异导入

发布时间:2020-12-20 13:52:59 所属栏目:Python 来源:网络整理
导读:从不同的路径导入相同的 Python模块似乎导致创建两个不同的模块引用. 例如,使用以下三个Python脚本. Script1和Script2位于OuterPackage中,TestWithGlobals位于SubPackage中. + Root|_+ OuterPackage | - Script1 | - Script2 |_+ SubPackage | - TestWithGlo
从不同的路径导入相同的 Python模块似乎导致创建两个不同的模块引用.

例如,使用以下三个Python脚本. Script1和Script2位于OuterPackage中,TestWithGlobals位于SubPackage中.

+ Root
|_+ OuterPackage
  | - Script1
  | - Script2
  |_+ SubPackage
    | - TestWithGlobals

SCRIPT1:

from OuterPackage.SubPackage import TestWithGlobals
import Script2
print TestWithGlobals.__name__

print TestWithGlobals.global_string
Script2.MakeStringBall()
print TestWithGlobals.global_string

和脚本2:

from SubPackage import TestWithGlobals
print TestWithGlobals.__name__

def MakeStringBall():
    TestWithGlobals.global_string = "ball"

最后是TestWithGlobals本身

global_string = "test"

现在,当运行Script1时,输出如下:

SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
test
test

从SubPackage更改为Script2中的OuterPackage.SubPackage将导致Script1的输出不同:

OuterPackage.SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
test
ball

在运行Script1之前,Root将附加到pythonpath.

为什么TestWithGlobals在Script1和Script2之间有所不同,同时引用了相同的模块?这背后的原因是什么?

解决方法

如果您按如下方式更改代码,则会更多地了解正在发生的事情:

Script1.py

import sys
from OuterPackage.SubPackage import TestWithGlobals
print "In Script1",id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
import Script2
print TestWithGlobals.__name__

print "TestWithGlobals:",TestWithGlobals.global_string
Script2.MakeStringBall()
print "TestWithGlobals:",TestWithGlobals.global_string
print "Script2.TestWithGlobals:",Script2.TestWithGlobals.global_string

Script2.py

from SubPackage import TestWithGlobals
print TestWithGlobals.__name__
import sys

def MakeStringBall():
    print "In MakeStringBall",id(TestWithGlobals)
    print "In MakeStringBall Subpackage.TestWithGlobals",id(sys.modules['SubPackage.TestWithGlobals'])
    print "In MakeStringBall OuterPackage.SubPackage.TestWithGlobals",id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
    TestWithGlobals.global_string = "ball"

这个输出是:

In Script1 4301912560
SubPackage.TestWithGlobals
OuterPackage.SubPackage.TestWithGlobals
TestWithGlobals: test
In MakeStringBall 4301912784
In MakeStringBall Subpackage.TestWithGlobals 4301912784
In MakeStringBall OuterPackage.SubPackage.TestWithGlobals 4301912560
TestWithGlobals: test
Script2.TestWithGlobals: ball

python中的导入系统构造新模块,并通过sys.modules缓存中的导入路径引用它们.在这种情况下,模块在2个不同的路径下导入,因此创建了2个不同的模块对象(正如您可以通过id函数的输出看到的).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读