How could I define a class such that the object name can be used as a variable? I am writing a class for numerical analysis, which contain only one numpy array as instant variable and many mathematical operations. For convenience and readability, it would be nice to access the numpy array simply by it's object name. For example, a numpy array (or objects from many other packages like matplotlib, pandas, etc...) can be called directly,
import numpy as np
foo = np.array([[1,2],[3,4]])
print foo
This is something like what I have (definition methods are omitted)
import numpy as np
class MyClass():
def __init__(self, input_array):
self.data = np.array(input_array)
foo = MyClass([[1,2],[3,4]])
print foo
print foo.data
This prints foo as pointer and content of foo.data
<__main__.MyClass instance at 0x988ff0c>
[[1 2]
[3 4]]
I tried self = np.array(input_array)
in the constructor but it still gives an address. I am thinking something like overloading object name but I couldn't find any information.
If it is not possible, then how could those packages achieve this? I tried to read some source code of numpy and pandas. But as a newbie to python, it's nearly impossible for me to find the answer there.
EDIT
Thanks for CoryKramer and Łukasz R. for suggestion of using __str__
and __repr__
. But I realized what I really needed was subclassing numpy.ndarray or even pandas DataFrame such that all mathematical functions are inherited. I found these two links very helpful, for ndarray and for DataFrame, to tweek __init__
calls for my interface.