为什么会出现NameError: name 'array' is not defined
我在使用spyder,并写了一个类:
class Ray:
def __init__(self, r, p, k):
if r.shape == (3,):
self.r = r
if p.shape == (3,):
self.p = p
if k.shape == (3,):
self.k = k
r = array(range(3))
p = array(range(3))
k = array(range(3))
这个类保存在/home/user/workspace/spyder/project这个文件夹里,控制台的工作目录也是这个。在控制台里,我可以运行一个数组(range(3)),它会返回一个包含0,1,2的数组。但是当我尝试
import ray
时,我遇到了以下错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ray.py", line 8, in <module>
class Ray:
File "ray.py", line 20, in ray
r = array(range(3));
NameError: name 'array' is not defined
补充说明:
默认情况下,spyder有这样的行为,我不太明白为什么array()会默认工作,我以为它只是numpy的一部分。
import numpy as np # NumPy (multidimensional arrays, linear algebra, ...)
import scipy as sp # SciPy (signal and image processing library)
import matplotlib as mpl # Matplotlib (2D/3D plotting library)
import matplotlib.pyplot as plt # Matplotlib's pyplot: MATLAB-like syntax
from mayavi import mlab # 3D plotting functions
from pylab import * # Matplotlib's pylab interface
ion() # Turned on Matplotlib's interactive mode
Within Spyder, this intepreter also provides:
* special commands (e.g. %ls, %pwd, %clear)
* system commands, i.e. all commands starting with '!' are subprocessed
(e.g. !dir on Windows or !ls on Linux, and so on)
1 个回答
13
你需要使用 from numpy import array
这行代码。
在Spyder这个工具里,它会自动帮你处理这些事情。但如果你在写一个程序,就必须自己添加需要的导入代码;这样做的好处是,其他没有安装Spyder的人也能运行你的程序。
我不太确定Spyder默认会为你导入哪些东西。array
可能是通过 from pylab import *
或者 from numpy import *
导入的。如果你想把Spyder控制台里的代码直接复制到你的程序里,可能需要用到 from numpy import *
或者 from pylab import *
。不过,官方不推荐在程序中这样做,因为这样会让程序的命名空间变得混乱;通常的做法是先用 import numpy as np
导入,然后用 np.array(…)
来调用。