Home » Learn Python » Dunder (Magic) Methods » Converting Objects to Strings

Converting Objects to Strings

You can make it possible to obtain a string representation of your objects by implementing the __str__ method in your classes.

This method must return a string representation of your object.

class Person:
    def __init__(self, name):
        self._name = name

    def __str__(self):
        return f"I am a person called '{self._name}'"
    
bob = Person("Bob")
print(bob)
I am a person called 'Bob'

The __repr__ Method

The purpose of __str__ is to return a human-readable “informal” representation of an object. You can tweak it as necessary, to provide reader-friendly output.

On the other hand, you can implements the __repr__ method to return a “formal” string version of your object, typically used during development and debugging, or possibly as part of the logic of your program.

The existence of the separate __str__ method means you can always change the reader-friendly string version without affecting the “official” string returned by __repr__.

Whereas str() returns the “informal” version of the string returned from __str__, the repr() function returns the formal string returned by __repr__.

class Person:
    def __init__(self, name):
        self._name = name

    def __str__(self):
        return f"I am a person called '{self._name}'"
    
    def __repr__(self):
        return f"Person [{self._name}]"
    

bob = Person("Bob")

informal_string = str(bob)
print(informal_string)

formal_string = repr(bob)
print(formal_string)
I am a person called 'Bob'
Person [Bob]

Leave a Reply

Blog at WordPress.com.

%d