Reputation: 8945
How to make a class return an object in the following way:
import numpy as np
a = np.array([(1,2),(3,4)])
Whenever a
is referenced, it returns
array([[1, 2],
[3, 4]])
However when I create a simple class:
class Example:
def __init__(self, data):
self.nparray = np.array(data)
And run b = Example([(1,2),(3,4)])
then reference b
I get: <__main__.Example at 0x7f17381099e8>
. To return the value I need to run b.nparray
.
How to make the class Example
return
array([[1, 2],
[3, 4]])
when b
is referenced?
I tried using methods such as __new__
, __repr__
and __getitem__
however none produced the desired behavior.
Upvotes: 0
Views: 66
Reputation: 160647
You should use __repr__
in the following way:
class Example:
def __init__(self, data):
self.nparray = np.array(data)
def __repr__(self):
return repr(self.nparray)
This returns the representation the self.nparray
object within:
>>> c = Example([(1, 2), (3, 4)])
>>> c
array([[1, 2],
[3, 4]])
Of course this is used and during interactive sessions where you simply enter the name and press enter and if you print it with print(c)
. If you need to limit to only for print
calls you define __str__
for the object in question.
Upvotes: 2
Reputation: 1
You can't return any data from a class init function. Have you tried something like:
class Example(object):
nparray = None
def __init__(self, data):
self.nparray = np.array(data)
return
def getArray(self):
return(self.nparray)
Upvotes: 0
Reputation: 11837
Using Python's "magic methods", like the __init__
you've already seen, we can make the class execute code when certain things happen. One of these is __call__
, which executes when the class is called like a function.
Knowing this, you could use this code:
import numpy as np
class Example:
def __init__(self, data):
self.nparray = np.array(data)
def __call__(self):
# This function is called when an instance of Example is called
return self.nparray
The result of this:
>>> b = Example([[1, 2], [3, 4]])
>>> b()
array([[1, 2],
[3, 4]])
For more on magic methods, see this useful article.
Upvotes: 2