[英]Why am I getting NameError: name 'array' is not defined
I'm using spyder and have written the following class: 我正在使用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))
It is stored in /home/user/workspace/spyder/project and the console working directory is that one. 它存储在/ home / user / workspace / spyder / project中,控制台的工作目录就是该目录。 In the console I can run an array(range(3)) and it returns an array with values 0,1,2.
在控制台中,我可以运行一个array(range(3)),它返回一个值为0,1,2的数组。 However when doing
但是当做
import ray
I get the following error 我收到以下错误
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
EDIT: 编辑:
by default spyder has the following behaviour, don't really understand why array() works by default I thought it was only part of numpy. 默认情况下,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)
You need from numpy import array
. 您需要
from numpy import array
。
This is done for you by the Spyder console. 这是由Spyder控制台为您完成的。 But in a program, you must do the necessary imports;
但是在程序中,您必须进行必要的导入; the advantage is that your program can be run by people who do not have Spyder, for instance.
优点是,例如,您的程序可以由没有Spyder的人运行。
I am not sure of what Spyder imports for you by default. 我不确定默认情况下Spyder会为您导入什么。
array
might be imported through from pylab import *
or equivalently through from numpy import *
. array
可以from pylab import *
或者等效地from numpy import *
。 If you want to directly copy code from the Spyder console to a program, you might need from numpy import *
or even from pylab import *
. 如果要将代码直接从Spyder控制台复制到程序,则可能需要
from numpy import *
甚至from pylab import *
。 It is officially not recommended to do this in a program , though, as this pollutes the program's namespace; 但是,我们不建议在程序中这样做 ,因为这会污染程序的名称空间。 doing
import numpy as np
and then np.array(…)
is customary. 习惯
np.array(…)
import numpy as np
,然后使用np.array(…)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.