我使用的是python3.2.3和numpy1.6.1。 如果有人能给我解释一下,当我试图(以两种不同的方式)访问NumPy数组的元素时,NumPy会做些什么。在
代码:
import numpy as np
class MyClass:
def __init__(self,q):
self.coord = q
self.firstel = q[0]
self.secondel = q[1:2]
q = np.array([10,20]) # numpy array
my_object = MyClass(q) # object of MyClass
print('original','q:',q,' / coord:',my_object.coord,' / 2elements:',my_object.firstel,my_object.secondel])
q[0],q[1] = 30,40 # modification of the elements of q
print('modified','q:',q,' / coord:',my_object.coord,' / elements:', my_object.firstel, my_object.secondel])
q
是一个numpy数组,我将其作为参数传递给MyClass
。我将它存储在类中名为coord
的变量中。然后我在类中以两种不同的方式访问q
的第一个和第二个元素。在
当我运行上面的代码时,我得到的是:
^{pr2}$当q
发生变化时,firstel
不会更新,但变量secondel
是。在
q[0]
和{
谢谢
firstel
变量是一个(不可变)值,因此从未更新:而
^{pr2}$secontel
变量是原始数组上的视图,因此将更新:一。在
解决此问题的一种方法是使
firstel
成为一种方法:这可能会让你更清楚firstel和
secondel
在你的类中的意图是什么。在安迪的解释恰到好处。至于如何克服这个限制,我不喜欢到处输入空括号,因此对于这种类属性,我更喜欢使用properties,可能受numpy的
shape
,dtype
等的影响:现在:
^{pr2}$相关问题 更多 >
编程相关推荐