3

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.

Community
  • 1
  • 1
SamKChang
  • 91
  • 1
  • 8

1 Answers1

5

You can define the __str__ method 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 here for detailed discussion of when it is appropriate to use __repr__ vs __str__ for your class.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 2
    It might be best to use `__str__()` instead; `__repr__()` should either return a valid Python expression or something in angle brackets. – Kevin Jul 16 '15 at 14:13
  • Perhaps I've misunderstood but doesn't the OP want to print the name of the class and have access to the data separately? – SuperBiasedMan Jul 16 '15 at 14:15