def __repr__(self):
return str(self._x)
The Python interpreter prints the repr
of the object by default.
Question
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
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 2
def __repr__(self):
return str(self._x)
The Python interpreter prints the repr
of the object by default.
OTHER TIPS
__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
Use dir. Especially from the cli, dir(t) would reveal as much as you need to know about your object t.