类内的Numpy数组赋值

2024-10-01 19:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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]和{}怎么了?在

谢谢


Tags: of代码selfnumpy元素objectmynp
2条回答

firstel变量是一个(不可变),因此从未更新:

self.firstel = q[0]  # and stays this value once and for all

secontel变量是原始数组上的视图,因此将更新:

^{pr2}$

一。在

解决此问题的一种方法是使firstel成为一种方法:

def firstel(self):
    return self.q[0]

这可能会让你更清楚firstel和secondel在你的类中的意图是什么。在

安迪的解释恰到好处。至于如何克服这个限制,我不喜欢到处输入空括号,因此对于这种类属性,我更喜欢使用properties,可能受numpy的shapedtype等的影响:

class MyClass(object):

    def __init__(self, q):
        self.coord = np.asarray(q)

    @property
    def firstel(self):
        """The first element of self.coord"""
        return self.coord[0]

    @property
    def secondel(self):
        """The second element of self.coord"""
        return self.coord[1]

现在:

^{pr2}$

相关问题 更多 >

    热门问题