Lzkatz
Lzkatz

Reputation: 173

Python - Pass instance function calls to attribute

I was attempting to write a customized numpy array wrapper that behaves like a numpy array 99% of the time, but has some additional indexing functionality for our specific use case. I was wondering if this type of behavior was possible.

Ideally, I'd be able to treat an instance of the class as one of it's attributes for all behavior except anything I specifically override. I'd like to be able to call all numpy functions on my wrapper class, except for some specific calls.

For example:

class LabeledArray(object):
    def __init__(self, array, label):
        self.array = array
        self.label = label

    def special_thing(self):
        print "I do a special thing here"

la = LabeledArray(np.zeros((5,2)), {'foo': 0, 'bar': 1})

la + 1
=> 
array([[1,1,1,1,1],
       [1,1,1,1,1]])

la.shape
=>
(5,2)

la.special_thing()
=>
"I do a special thing here"

Essentially, i'd like to preserve the benefits of numpy (broadcasting etc) with a few custom side tweaks.

I do realize I could just do la.array + 1, but I wanted to see if there was any way to abstract away that layer.

Thank you!

Upvotes: 0

Views: 42

Answers (1)

datawrestler
datawrestler

Reputation: 1567

Numpy has docs on subclassing. An example of a construct you can use to accomplish this is:

class LabeledArray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        return super(LabeledArray, cls).__new__(cls, *args, **kwargs)

    def special_thing(self):
        print('I do a special thing here')

LA = LabeledArray(shape=(2, 2), dtype=float, order='F')
LA.special_thing()
# I do a special thing here

Upvotes: 1

Related Questions