Python module __str__() and __repr__() functions are used to convert class object into string. These functions can be are very helpful in debugging by logging useful information of the object.

_str_ Function

It is called by str() and the built-in functions format() and print() to compute printable string representation of an object. The return value must be a string object. Default implementation defined by the built-in type object calls object.__repr().

_repr_ Function

It is called by the repr() built-in function to compute the string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value. The return value must be a string object. It is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

Use __str__() goal is to create human friendly string representation of object, __repr__() goal is to be unambiguous string representations.

_bytes_ Function

It is called by bytes to compute a byte-string representation of an object. It should return a bytes object.

Example

Below example demonstrate the conversion of class object to its corresponding sting representation. Person class has two member fname and lname. This class provides its own implementation of __repr__(), __str__() and __byte__ function. __repr__() returns unambiguous representation of the object. __str__() gives an informal representation (more readable) but may not be always unambiguous.

__bytes__() function converts string representation of the object to bytes using UTF-8 encoding.

 class Person():
    def __init__(self):
        self.fname = "Hello"
        self.lname = "Python"

    # Create string useful for debugging
    def __repr__(self):
        return "<Person Class - fname:{0}, lname:{1}>".format(self.fname, self.lname)

    # Create human-readable string
    def __str__(self):
        return "Person ({0} {1})".format(self.fname, self.lname)

    # Convert the informal string to a bytes object
    def __bytes__(self):
        val = "Person:{0}:{1}".format(self.fname, self.lname)
        return bytes(val.encode('utf-8'))

def main():

    # Create Person object
    cls1 = Person()

    # Convert to a string using __repr__
    print(repr(cls1))

    # Output
    # <Person Class - fname:Hello, lname:Python>

    # Convert to a string using __str__
    print(str(cls1))

    # Output
    # Person (Hello Python)

    # Convert to a string using __bytes__
    print(bytes(cls1))

    # Output
    # b'Person:Hello:Python'

if __name__ == "__main__":
    main()