假设我有三个文件:
a.py
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'未定义
但是,a在sys.modules中存在:
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就能正常运行了。
由此引发了一些问题:
为什么Python说它不知道a是什么,而它在sys.modules中存在?
使用sys.modules访问类和函数定义是否是一种“正确”的方式?
导入模块的“正确”方法是什么?
例如:
from module import x
或者
import module