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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With