Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
sanguineturtle Avatar asked Dec 07 '22 03:12

sanguineturtle


1 Answers

__repr__ is intended to be the literal representation of the object.

Note that if you define __repr__, you don't have to define __str__, if you want them both to return the same thing. __repr__ is __str__'s fallback.

class test:
    def __init__(self):
        self._x = 2
    def __repr__(self):
        return str(self._x)
    def __call__(self):
        return self._x

t = test()

>>> print t
2

>>> t
2
like image 74
Russia Must Remove Putin Avatar answered Dec 11 '22 11:12

Russia Must Remove Putin