liveBook · Manning

__str__

As explained in Python How-To

__str__ is a Python special method that returns an informal, user-oriented string representation of an object.

How can a class show useful information when you print one of its instances? Without a custom string representation, printing an instance may show only its class and memory address. Define __str__ to provide a descriptive, user-oriented alternative. section 8.4.1

Listing 8.10 Overriding __str__ in a class
class Task:
   def __init__(self, title, desc, urgency):
       self.title = title
       self.desc = desc
       self.urgency = urgency

   def __str__(self):
       return f"{self.title}: {self.desc}, urgency level {self.urgency}"

A Task instance stores a title, description, and urgency. Its __str__ method combines those attributes into a readable string and returns it. section 8.4.1

Display an instance

With task = Task("Laundry", "Wash clothes", 3), print(task) outputs Laundry: Wash clothes, urgency level 3. An f-string such as f"Next Task - {task}" uses the same method. Use str(task) when you want the string explicitly. section 8.4.1

Keep these distinctions in mind:

  • __str__ is an instance method. It must return a str containing descriptive information about that instance. section 8.4.1
  • __repr__ serves developers inspecting an object, including in an interactive console; __str__ serves ordinary display. In f-strings, {instance!r} requests __repr__, while {instance!s} requests __str__. section 8.4.3
  • Consider implementing both methods. If you implement only __repr__, Python uses it when __str__ is absent. section 8.4.4
Listing 9.2 Adding a custom method
class Direction(Enum):
   NORTH = 0
   SOUTH = 1
   EAST = 2
   WEST = 3

   def __str__(self):
       return self.name.lower()


def move_to(direction: Direction, distance: float):
   if direction in Direction:
       message = f"Go to the {direction} for {distance} miles"
   else:
       message = "Wrong input for direction"
   print(message)

move_to(Direction.NORTH, 3)
# output: Go to the north for 3 miles

The same technique works for enumeration members: returning self.name.lower() changes an f-string’s displayed direction from Direction.NORTH to north. section 9.1.4

How Python How-To covers it

How deep it goes
Works through an instance-method implementation, its str return value, invocation paths, and its distinction from __repr__.
Examples
Shows a Task with title, description, and urgency, plus a Direction enumeration displayed as a lowercase direction.
What it assumes
Assumes basic class instances and attributes while explaining how overriding a special method changes their display.
What you can do after
Build it from scratch: define __str__ for a class or enumeration to produce readable instance output.
How it connects
Connects special methods and method overriding to print, f-strings, str(), __repr__, and enumeration classes.

Also explained in

Compare how 3 books explain __str__ →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.