Reputation: 837
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
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
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