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, !r in 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:

  1. print(r) shows Rune ember (power 7)
  2. repr(r) is Rune('ember', 7)