从NumPy数组继承的类如何更改其自己的值? [英] How can a class that inherits from a NumPy array change its own values?

查看:139
本文介绍了从NumPy数组继承的类如何更改其自己的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,它继承自NumPy n维数组.我想拥有两个可以更改该类实例的数组值的类方法.一种方法应将类实例的数组设置为类实例的列表数据属性的值,另一种方法应将一些列表值附加到类实例的数组.我不确定如何做到这一点,但是我的尝试如下:

I have a simple class that inherits from the NumPy n-dimensional array. I want to have two methods of the class that can change the array values of an instance of the class. One of the methods should set the array of the class instance to the values of a list data attribute of the class instance and the other of the methods should append some list values to the array of the class instance. I'm not sure how to accomplish this, but my attempt is as follows:

import numpy

class Variable(numpy.ndarray):

    def __new__(cls, name = "zappo"):
        self = numpy.asarray([]).view(cls)
        self._values            = [1, 2, 3] # list of values
        return(self)

    def updateNumPyArrayWithValues(self):
        self = numpy.asarray(self._values)

    def appendToNumPyArray(self):
        self = numpy.append(self, [4, 5, 6])

a = Variable()
print(a)
a.updateNumPyArrayWithValues()
print(a)

作为一个快速的先发问题,此类是否可以在标准的NumPy数组操作(例如以下内容)中存活下来?:

As a quick, preemptive question, would this class survive standard NumPy array operations such as the following?:

>>> v1 = np.array([23, 20, 13, 24, 25, 28, 26, 17, 18, 29])
>>> v1 = v1[v1 >= 20]

那么,我可以对我的类做类似的事情,并保留其所有数据属性吗?

So, could I do similar things with my class and have all of its data attributes retained?

推荐答案

您可以这样做:

class Variable(np.ndarray):

    def __new__(cls, a):
        obj = np.asarray(a).view(cls)
        return obj

    def updateNumPyArrayWithValues(self):
        self[1] = 1
        return self

>>> v = Variable([1,2,3])
>>> v
Variable([1, 2, 3])
>>> v.updateNumPyArrayWithValues()
Variable([1, 1, 3])
>>> v[v>1]
Variable([3])

这篇关于从NumPy数组继承的类如何更改其自己的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆