有效的模塊,您需要在一些地方把你的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