hainabaraka
hainabaraka

Reputation: 837

example of python console output different from print

I would like to have an example of a variable myvar that outputs two different things when, on the python interactive console:

>>> myvar

versus

>>> print(myvar)

Upvotes: 2

Views: 262

Answers (3)

wjandrea
wjandrea

Reputation: 33179

The REPL gets the __repr__() while print() gets the __str__(), so any object that implements the methods differently will appear different, for example:

class Foo:
    def __str__(self):
        return 'STR!'

    def __repr__(self):
        return 'REPR!'
>>> f = Foo()
>>> f
REPR!
>>> print(f)
STR!

(Just to be clear, this wouldn't be a good repr in practice.)


Two real-life examples are datetime.datetime and the NumPy array:

>>> from datetime import datetime as dt
>>> d = dt.now()
>>> d
datetime.datetime(2021, 10, 10, 13, 44, 25, 491020)
>>> print(d)
2021-10-10 13:44:25.491020
>>> import numpy as np
>>> a = np.zeros(5)
>>> a
array([0., 0., 0., 0., 0.])
>>> print(a)
[0. 0. 0. 0. 0.]

Upvotes: 3

JChris
JChris

Reputation: 1678

It all depends on how you return __str__ and __repr__, for example:

class MyClass:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"I'm {self.name}"

    def __repr__(self):
        return f"<Name {self.name}>"

Returns:

>>> from test import MyClass
>>> myvar = MyClass("John")
>>> myvar
<Name John>
>>> print(myvar)
I'm John

Upvotes: 2

vht981230
vht981230

Reputation: 5146

>>> myvar = "abc"
>>> myvar
'abc'
>>> print(myvar)
abc
>>> 

Upvotes: 0

Related Questions