0

I'm creating a class that inherits from a NumPy ndarray. I'm having a bit of trouble giving it methods. Specifically, when I add a simple method printout to the class, I get the following error:

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

How should I be adding methods to this class? Also, preemptively, is there a recommended way to change the value of self internally in this class?

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()
2
  • .view does not return anything Commented Dec 19, 2014 at 16:41
  • 2
    If you're using __new__, you have to return the newly created instance of your class. Commented Dec 19, 2014 at 16:42

1 Answer 1

2

As @sebastian said, new must return the instance you create. Just add return self at the end of the constructor (I've tested it and it worked for me):

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

   return self
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks very much for your help with that. Inheriting from NumPy arrays is certainly a bit different from usual Python inheriting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.