Home > Enterprise >  What does object.__str__ and object.__repr__ do? Warning: It's not the same as Class.__str__ an
What does object.__str__ and object.__repr__ do? Warning: It's not the same as Class.__str__ an

Time:04-25

class TestClass:
    def __init__(self):
        pass
    def __str__(self):
        return 'You have called __str__'
    def __repr__(self):
        return 'You have called __repr__'

a = TestClass()
print(object.__repr__(a))
print(object.__str__(a))

Output:

<__main__.TestClass object at 0x7fe175c547c0>
You have called __repr__

What does those two functions do?


My understanding is that calling str(a) returns a.__str__() and calling repr(a) returns a.__repr__(). print(a) also prints the string, a.__str__() since there is an implicit str(a) conversion going on.

Note that my question is not a duplicate to another popular question; see my first comment below.

The behaviour is COUNTERINTUITIVE; doing print(object.__str__(a)) prints the repr string instead of the str string.

CodePudding user response:

The object class provides default implementations for the __repr__ and __str__ methods.

  • object.__repr__ displays the type of the object and its id (the address of the object in CPython)
  • object.__str__(a) calls repr(a). The rationale is that if __str__ is not overriden in a class str(a) will automatically call repr(a), using a possible override of __repr__

This is exactly what happens here because you are directly calling object.__str__ while this is not expected.

  • Related