liveBook · Manning

String conversion

As explained in Python How-To

A string representation is textual output that describes the value or identity of an object.

How can a class produce useful text instead of a default object address? Define __str__ for readable instance output and __repr__ for representation that describes how the instance was created. section 8.4 section 8.4.1 section 8.4.2

Choose the conversion method according to where the text will appear:

  • Override __str__ as an instance method that returns a str containing descriptive attributes. print(task), str(task), and f"{task}" use this representation. section 8.4.1
  • Override __repr__ as an instance method that returns a string describing instantiation. Interactive console display and repr(task) use this representation. section 8.4.2
  • Keep __str__ readable for users and __repr__ informative for developers; defining both gives users and developers proper representations. section 8.6

A readable Task instance

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}" def __repr__(self): return f"Task({self.title!r}, {self.desc!r}, {self.urgency})" Task("Laundry", "Wash clothes", 3) # Task('Laundry', 'Wash clothes', 3) print(task) # Laundry: Wash clothes, urgency level 3 section 8.4.1 section 8.4.2

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}"

Inspect the complete __str__ implementation for a Task class and its formatted attribute output. section 8.4.1

How Python How-To covers it

How deep it goes
Distinguishes __str__ from __repr__, specifies return requirements, and demonstrates both overrides with a Task class.
Examples
Uses a Task object with title, description, and urgency fields to demonstrate print, f-string interpolation, str(), repr(), and console display.
What it assumes
Assumes familiarity with classes and instances while introducing special-method overriding and the distinct roles of __str__ and __repr__.
What you can do after
Build it from scratch by overriding __str__ and __repr__ for readable display and informative instance representations.
How it connects
Connects string conversion with classes, instances, special methods, inheritance, print, f-strings, and interactive consoles.

Also explained in

Compare how 2 books explain string conversion →

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.