Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define class output in ipython console

Let's say I have the following code:

class PrintStuff:
    def __init__(self,stuff):
        self._stuff = stuff

    def __str__(self):
        return self._stuff

If I make an instance of it in ipython and type the name of the instance, it prints out what appears to be the name of the class and the location of it in memory. However if I put the instance into the print function, it prints out as expected:

pstuff = PrintStuff('print this stuff')

pstuff
Out[44]: <__main__.PrintStuff at 0x7fae0531de80>

print(pstuff)
print this stuff

How would I go about making it so that the ipython console prints the same stuff that the print function does? For example, a pandas series has the type of behavior I am looking for:

series = pd.Series({'x':[1,2],'y':[2,3],'z':[3,4]})

series
Out[47]: 
x    [1, 2]
y    [2, 3]
z    [3, 4]
dtype: object

print(series)
x    [1, 2]
y    [2, 3]
z    [3, 4]
dtype: object
like image 875
jammertheprogrammer Avatar asked Dec 01 '25 02:12

jammertheprogrammer


1 Answers

You need to add a __repr__:

By default, the Object __repr__ returns the type and memory address, this is what you see when the console outputs (for instance):

<__main__.PrintStuff at 0x7fae0531de80>

After overloading the __repr__, you control what the output is.

class PrintStuff:
    def __init__(self,stuff):
        self._stuff = stuff

    def __str__(self):
        return self._stuff

    def __repr__(self):
        return str(self)


pstuff = PrintStuff('print this stuff')
pstuff

output:

print this stuff
like image 137
Reblochon Masque Avatar answered Dec 02 '25 15:12

Reblochon Masque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!