Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default print method of a class when called in a console?

Tags:

python

In a Python interactive console (IDLE, IPython, etc), if I enter a variable name by itself, I will get back the equivalent of printing that variable.

In [1]: foo = {'a':1, 'b':2}
In [2]: foo
Out [2]: {'a':1, 'b':2}
In [3]: print(foo)
Out [3]: {'a':1, 'b':2}

I'd like to incorporate this functionality into a container class, like:

class Foo():
    def __init__(self, bar):
        self.bar = bar
    def __mysteryfunction__(self)
        print(self.bar)

I'd like the class to print as before, but instead I get:

In [1]: foo = Foo({'a':1, 'b':2})
In [2]: foo
Out [2]: <__main__.foo at 0x1835c093128>

I've searched for nearly every permutation I can think of for what this might be called, and haven't found the same question. Is this a class method like I'm hoping, or something built into the console interpreter? If the latter, can it be modified?

like image 530
mirrorcoloured Avatar asked Oct 16 '25 00:10

mirrorcoloured


1 Answers

For print x, x.__str__ is called. For output in a REPL when an object is returned, x.__repr__ is called.

Read about str and repr functions.

like image 77
9000 Avatar answered Oct 18 '25 17:10

9000



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!