__str__ and instances as return values

20-minute lesson · module-classes-04

You are previewing this course as a guest

Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.

Sign in

__str__ and instances as return values

20-minute lesson · module-classes-04

  • Define `__str__` so `print` and `str()` show a readable description.
  • Explain why the default object representation is unhelpful.
  • Write a method that returns a brand-new instance instead of mutating.
  • Contrast a mutating method with one that returns a fresh object.

Source attribution

Status: adapted

How to Think Like a Computer Scientist: Interactive Edition source · Classes and Objects - the Basics / The __str__ Method / Instances as Return Values

Adaptation notes. Reading rewritten in our voice. A Point class gets a __str__ and a `shifted` method that returns a new Point. Hidden tests check the string form and that returning-a-new-instance leaves the original unchanged.

License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.