假设我有 3 个文件:
a.py
from d import d
class a:
def type(self):
return "a"
def test(self):
try:
x = b()
except:
print "EXCEPT IN A"
from b import b
x = b()
return x.type()
b.py
import sys
class b:
def __init__(self):
if "a" not in sys.modules:
print "Importing a!"
from a import a
pass
def type(self):
return "b"
def test(self):
for modules in sys.modules:
print modules
x = a()
return x.type()
c.py
from b import b
import sys
x = b()
print x.test()
并运行 python c.py
Python 回来抱怨:
NameError:全局名称“a”不是
定义的
但是,sys.modules 中有一个 IS:
copy_reg
sre_compile
locale
_sre
functools
encodings
site
__builtin__
operator
__main__
types
encodings.encodings
abc
errno
encodings.codecs
sre_constants
re
_abcoll
ntpath
_codecs
nt
_warnings
genericpath
stat
zipimport
encodings.__builtin__
warnings
UserDict
encodings.cp1252
sys
a
codecs
os.path
_functools
_locale
b
d
signal
linecache
encodings.aliases
exceptions
sre_parse
os
我可以更改 b.py 以便:
x = a()
更改为
x = sys.modules["a"].a()
python 会很乐意运行它。
由此产生了几个问题:
当 a 位于 sys.modules 中时,为什么 python 说它不知道 a 是什么?
使用 sys.modules 是访问类和函数定义的“正确”方法吗?
导入模块的“正确”方法是什么?
IE
从模块导入x
or
导入模块
我想这是一个作用域问题,如果您在构造函数中导入模块,则只能在导入语句之后在构造函数中使用它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)