toing
toing

Reputation: 536

how to have a property setter for a nd-array or matrix in python?

I am not sure how can I achieve setting a nd array/matrix in the following syntactic way instead of complicated workaround. Any help is appreciated. Thanks

for example:

import numpy as np

class myExample:
    def __init__(self):
        self._matrix = np.empty([2,2])

    @property
    def matrix(self, row_id=None, col_id=None):
        if row_id == None or col_id == None:
            return self._matrix
        else:
            return self._matrix[row_id, col_id]

    @matrix.setter
    def matrix(self, row_id, col_id, new_val):
        print("{}{}".format(row_id, col_id)
        self._matrix[row_id, col_id] = new_val

Test = myExample()
Test.matrix[1,2] = 3

Upvotes: 1

Views: 1736

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46911

why not inherit from np.array?

import numpy as np

class myExample(np.ndarray):
    def __new__(cls):
        zero = np.zeros((2, 4), dtype=np.int)
        obj = np.asarray(zero).view(cls)
        return obj

Test = myExample()
Test[1,2] = 3
print(Test)

that way you get the getters and setters (__getitem__/__setitem__) for free.

(note that your index [1, 2] is out of bounds for your shape [2, 2]).


and your example actually works if you just have a getter; you return an np.array that already has the needed properties:

import numpy as np

class myExample:
    def __init__(self):
        self._matrix = np.empty([3, 4])

    @property
    def matrix(self):
        return self._matrix


Test = myExample()
Test.matrix[1,2] = 3

update after OP's comments: if you need to print your matrix (or do other things) before setting the items you could try this:

import numpy as np

class myExample:
    def __init__(self):
        self._matrix = np.zeros([3, 4])

    @property
    def matrix(self):
        return self._matrix

    def __setitem__(self, key, value):
        print(self._matrix)  # or other things...
        self._matrix[key] = value

Test = myExample()
Test[1, 3] = 5

Upvotes: 3

Related Questions