Search code examples
pythonoopmethodspandasrepresentation

How to get Python Class to Return Some Data and not its Object Address


Context:

Using the following:

class test:
    def __init__(self):
        self._x = 2

    def __str__(self):
        return str(self._x)

    def __call__(self):
        return self._x

Then creating an instance with t = test()

I see how to use __str__ for print:

>>> print t
2

I can see how to make the object callable using __call__

>>> t()
2

Question

But how do you get the object to return an internal attribute such that when you enter:

>>> t
2

instead of:

<__main__.test instance at 0x000000000ABC6108>

in a similar way that Pandas prints out DataFrame objects.


Solution

  • Define __repr__.

    def __repr__(self):
        return str(self._x)
    

    The Python interpreter prints the repr of the object by default.