如何为从NumPy ndarray继承的类创建方法?

时间:2014-12-19 16:32:17

标签: python class inheritance numpy methods

我正在创建一个继承自NumPy ndarray的类。给它方法我有点麻烦。具体来说,当我向类添加一个简单的方法printout时,我收到以下错误:

AttributeError: 'NoneType' object has no attribute 'printout'

我应该如何向这个类添加方法?另外,还有一种推荐的方法是在这个类中内部更改self的值吗?

import numpy

class Variable(numpy.ndarray):

    def __new__(
        cls,
        name                    = "trk_pt",
        tree                    = None, # tree object
        eventNumber             = None,
        eventWeight             = None,
        numberOfBins            = None, # binning
        binningLogicSystem      = None, # binning
        ):
        self = numpy.asarray([]).view(cls)
        # 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

    def printout(
        self
        ):
        print("hello world")

a = Variable()
a.printout()

1 个答案:

答案 0 :(得分:2)

正如@sebastian所说, new 必须返回您创建的实例。只需在构造函数的末尾添加return self(我已对其进行了测试,它对我有用):

   ...
   self._values            = [] # list of values
   self._valuesRaw         = [] # list of unmodified, raw values

   return self