python - 应该如何创建一个继承自 NumPy ndarray 并具有默认值的类?

标签 python arrays inheritance numpy instantiation

我想创建一个继承自 NumPy ndarray 的类,并且我希望以这样一种方式执行此操作,即我不需要在实例化时为数组提供值,但可以将其默认为某个值。我在让它工作时遇到了一些困难:

import numpy

class Variable(numpy.ndarray):

    def __init__(
        self,
        name                    = "trk_pt",
        tree                    = None, # tree object
        eventNumber             = None,
        eventWeight             = None,
        numberOfBins            = None, # binning
        binningLogicSystem      = None, # binning
        ):
        # arguments
        self._name              = name
        self.tree               = tree
        self.eventNumber        = eventNumber
        self.eventWeight        = eventWeight
        self.numberOfBins       = numberOfBins
        self.binningLogicSystem = binningLogicSystem
        # internal
        self.variableObject     = None
        self.variableType       = None
        self.dataType           = None
        self.variableDataTypes  = None
        self.canvas             = None
        self.histogram          = None
        self._values            = [] # list of values
        self._valuesRaw         = [] # list of unmodified, raw values
        # NumPy ndarray inheritance
        #self = ([1])
        if sys.version_info >= (3, 0):
            super().__init__([1])
        else:
            super(numpy.ndarray, self).__init__([1])

a = Variable()

我遇到的错误如下:

TypeError: Required argument 'shape' (pos 1) not found

如何编写代码,使数组在实例化时具有默认值并且不需要值?

最佳答案

使用 this example from the docs as a guide , 你可以使用

    self = np.asarray([1]).view(cls)

__new__中实例化数组:

import numpy as np

class Variable(np.ndarray):

    def __new__(
        cls,
        name                    = "trk_pt",
        tree                    = None, # tree object
        eventNumber             = None,
        eventWeight             = None,
        numberOfBins            = None, # binning
        binningLogicSystem      = None, # binning
        ):
        self = np.asarray([1]).view(cls)
        self._name              = name
        self.tree               = tree
        self.eventNumber        = eventNumber
        self.eventWeight        = eventWeight
        self.numberOfBins       = numberOfBins
        self.binningLogicSystem = binningLogicSystem
        ...
        return self

a = Variable()

还要注意 help(np.ndarray)

No __init__ method is needed because the array is fully initialized after the __new__ method.

关于python - 应该如何创建一个继承自 NumPy ndarray 并具有默认值的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27557029/

相关文章:

python - 如何在脚本中列出与导入对应的 PyPI 包的名称?

C++ 两个矩阵的乘法

java - 更改父类(super class)从子类实现的接口(interface)的值会影响所有实例

python - 如何在 Python 中调用特定基类的方法?

c# - 如何在 C# 中评论/记录覆盖?

python - OpenCV 错误 : Assertion failed (size. 宽度>0 && size.height>0) python

python - 获取给定位置周围的单词

python - 如何关闭 SQLAlchemy implicit_returning?

ruby-on-rails - Rails 3 has_many - 在 View 中使用

java - 在Java中读取字符串中的字符时遇到问题