有效的模块,您需要在一些地方把你的import语句中所需要的范围:
import import_module
class local_class():
def local_function():
action = raw_input()
if action = 'fow':
import_module.import_function
else:
print 'null'
或
class local_class():
def local_function():
import import_module
action = raw_input()
if action = 'fow':
import_module.import_function
else:
print 'null'
# import_module.import_function would fail here, import_module is local
# to local_class.local_function
# BUT...
但要小心,一旦导入,模块将被python内部存储,这样即使你不能在另一个范围内访问它,如果你再次导入模块,你将得到相同的实例。例如:
>>> def func():
import shutil
# Store a new attribute in the module object
shutil.test = 5
print(shutil.test)
>>> func()
5
>>> shutil.test
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
shutil.test
NameError: name 'shutil' is not defined
>>> import shutil
>>> shutil.test # The attribute exists because we get the same module object
5
>>>
>>> ================================ RESTART ================================
>>> shutil.test
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
shutil.test
NameError: name 'shutil' is not defined
>>> import shutil
>>> shutil.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
shutil.test
AttributeError: 'module' object has no attribute 'test'
>>>
是的,但您需要实际导入它。这是你的实际代码吗? – That1Guy
我注意到你还没有接受任何答案。如果答案解决了你的问题,你应该[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),给你和答案者一些声望。 – sloth