
Fill in
Name Tags: __str__ & __repr__
Print an object without any help and you get something unhelpful like
<__main__.Rune object at 0x10a3f2d0>. Two special methods fix that:
__str__is the friendly version for users.print(),str()and f-strings use it.__repr__is the developer version, for debugging. The REPL,!rin f-strings, and items inside lists and dicts use it. By convention it looks like the code that would recreate the object.
class Island:
def __init__(self, name):
self.name = name
def __str__(self):
return f"the island of {self.name}"
def __repr__(self):
return f"Island({self.name!r})"
home = Island("Mossreach")
print(home) # the island of Mossreach
print([home]) # [Island('Mossreach')]
Pip tip: if you only write one, write
__repr__. When there's no__str__, Python falls back to__repr__.
Assignment
Replace each ___ so that:
print(r)showsRune ember (power 7)repr(r)isRune('ember', 7)
Replace each ___ so that:
print(r)showsRune ember (power 7)repr(r)isRune('ember', 7)
main.py Python sleeping
Press Run to try your code, then Check to test it.