1

I have created a class called Tensor

import numpy as np

class Tensor:
    def __init__(self, data):
        self.data = np.array(data)

and I'd like to set elements of a numpy array using Tensor:

x = np.array([[1,2,3,4],[4,3,2,1]])
x[:,::2] = Tensor([[0,0],[1,1]])

but it results an error ValueError: setting an array element with a sequence.

one workaround is to retrieve Tensor's data attribute: x[:,::2] = Tensor([[0,0],[1,1]]).data, but I'd like to know how to do it without manually retrieving anything, like when you can set values with a list or numpy array: x[:,::2] = [[0,0],[1,1]] or x[:,::2] = np.array([[0,0],[1,1]])

1 Answer 1

3

Numpy array objects all follow a protocol, as long as you implement __array__ method, you can use the object as an array:

>>> class Tensor:
...     def __init__(self, data):
...         self.data = np.array(data)
...     def __array__(self, dtype=None):
...         return self.data    # self.data.astype(dtype, copy=False) maybe better
...
>>> x[:,::2] = Tensor([[0,0],[1,1]])
>>> x
array([[0, 2, 0, 4],
       [1, 3, 1, 1]])

Reference: Writing custom array containers

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

2 Comments

Thanks for your answer it works! BTW, what is the use of dtype=None? when I delete it it results a TypeError: __array__() takes 1 positional argument but 2 were given. When do you have to specify a dtype? Thanks!
@Sam-gege This is the signature format required by numpy. Usually, different dtype expect to get arrays of corresponding data types.

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.