__str__()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jan 14, 2023
Contribute to Docs

The __str__() dunder method returns a reader-friendly string representation of a class object. It can be called with the built-in str() and print() functions. Unlike __repr__(), it is not necessary that __str__() return a valid Python expression.

Syntax

class ClassName:
  def __str__(self):

The __str__() method accepts no parameters. self is an implicit reference to the instance of ClassName.

Codebyte Example

The example below showcases various ways the __str__() can be called using an object literal, the built-in str() function, and the __str__() dunder method. All return the same string output; the aim is to make the output readable:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy