python中的import一個注意事項

 1 import math
 2  
 3 def foo():
 4     import math
 5     x = math.pi
 6     # 若是math在下面import會出錯,由於import是個寫的過程(添加到sys.modules中),會把math做爲
 7     # 局部空間變量,上面就找不到了
 8     #import math
 9     print math.sin(x)
10  
11 foo()

上例中函數中的import應該在使用它的地方以前,由於此次import會把math做爲局部變量訪問函數

不推薦在文件頭把全部的文件都import,由於會花費較多的時間,放在函數開頭的地方便可。spa

相關文章
相關標籤/搜索