You can memorize these two rules, and everything will be merry and well.
When you see
>>> EXPR
you can think of this as doing exactly the following (for the purposes of 61A):
if EXPR is not None:
print(repr(EXPR))
>>> class A:
>>> def __repr__(self):
>>> return "A"
>>> A() # print(repr(A()))
A
>>> repr(A()) # print(repr(repr(A())))
'A'
When you see
print(EXPR)
you can think of this as doing exactly the following:
thing_to_output = str(EXPR)
- cut off the quotes in
thing_to_output
, and print that to the terminal.
>>> print("hi") # 1: "hi"; 2: chop off quotes, so we get just hi
hi
>>> print(A()) # 1. str defaults to repr, so we get "A"; 2: chop off quotes, so we get just A
A
For the built-in str
,
__str__
returns itself
__repr__
returns an extra set of quotes around itself.
>>> str("a string")
'a string'
>>> repr("a string")
"'a string'"
```py