How to use object name as variable in python

How can I define a class so that the object name can be used as a variable? I am writing a numerical analysis class that contains only one numpy array as an instant variable and many math operations. For convenience and readability, it would be nice to access the numpy array simply by the object name. For example 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 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 outputs foo as a pointer and the contents of foo.data p>

<__main__.MyClass instance at 0x988ff0c>
[[1 2]
 [3 4]]

      

I tried self = np.array(input_array)

in the constructor but it still gives the address. I am thinking something like overloading the object name, but I couldn't find any information.

If this is not possible, then how can these packages achieve this? I tried to read some numpy and pandas source code. But being a python newbie it is almost impossible for me to find the answer.

EDIT

Thanks for CoryKramer and Łukasz R. for suggesting to use __str__

and __repr__

. But I realized that I really needed to subclass numpy.ndarray or even pandas DataFrame in order for all math functions to inherit. I found these two links very helpful, for ndarray and for DataFrame , to tweek __init__

calls to my interface.

+3


source to share


1 answer


You can define a method __str__

if you want to be able to represent your class object in a printable way

class MyClass():
    def __init__(self, input_array):
        self.data = np.array(input_array)
    def __str__(self):
        return str(self.data)

>>> foo = MyClass([[1,2],[3,4]])
>>> print(foo)
[[1 2]
 [3 4]]

      



Also, you can see a detailed discussion here of when it is appropriate to use __repr__

vs __str__

for your class.

+5


source







All Articles