__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See also documentation for repr() (which calls __repr__). __repr__ is more for developers, while __str__ is for end users.
A simple example (interactive):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
cls = self.__class__.__name__
return f'{cls}(x={self.x!r}, y={self.y!r})'
p = Point(1, 2)
p
Output:
Point(x=1, y=2)
Answer from Miki Tebeka on Stack OverflowA beginner's guide to __str__ and __repr__
A beginner's guide to __str__ and __repr__ : r/learnpython
[Python] What's the difference between __str__ and __repr_?
repr function
__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See also documentation for repr() (which calls __repr__). __repr__ is more for developers, while __str__ is for end users.
A simple example (interactive):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
cls = self.__class__.__name__
return f'{cls}(x={self.x!r}, y={self.y!r})'
p = Point(1, 2)
p
Output:
Point(x=1, y=2)
This is explained quite well in the Python documentation:
repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a__repr__()method.
So what you're seeing here is the default implementation of __repr__, which is useful for serialization and debugging.
Hi all, I made a couple of comments on another thread recently and I thought I'd pull them out into their own post for increased visibility. The intent here is to showcase some of Python's intermediate features in a beginner-friendly manner to get people thinking about how Python works under the hood. If you like this format please let me know and I can post more long-form answers in their own threads in the future.
Q: [<main.Test object at 0x123731860>, <main.Test object at 0x123731940>]
Why am I getting a weird output for print(c)?
Answer, part 1: You need to define a custom __repr__ function for your class to tell Python how to print it. By default it will just print the class and the memory location, which is the 'weird output' you're seeing here.
Full example:
class Test:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __repr__(self):
return f"Test({self.x=}, {self.y=}, {self.z=})"
>>> a = Test(1, 2, 3)
>>> print(a)
Test(self.x=1, self.y=2, self.z=3)Q:
How do lists print their strings?
Great question! To answer this in sufficient detail, we first need to discuss the difference between __str__ and __repr__.
__repr__, which I mentioned in my previous comment, is designed to be a full representation of an object - Essentially, by convention, it should contain everything required to disambiguate one object from another, and usually it's a string copy of the arguments used to construct the object in the first place.
__str__ on the other hand is the human-readable alternative, useful for very complex objects where we only want to display basic pieces of information for the purposes of logging or user interaction.
Now, when we do print(lst), the print function will make a call to the in-built function str - You'll probably recognize this function as we use it a lot to convert objects to strings! str(lst) will then delegate to lst.__str__(), which is our __str__ method.
The __str__ method of the list class looks (as a massive simplification) something like this - Note I've avoided using f-strings for clarity here, although they are the best-practice method for modern Python string formatting. (And yes, in reality the code below would be implemented in C, and it will use iter(self) to iterate over the items in the sequence)
def __str__(self):
return '[' + ', '.join(repr(item) for item in self.items) + ']'
You'll see here that we, again, delegate the string representation of every item in the list down to item.__repr__. Why use __repr__ rather than __str__ for child items? It's to avoid including special characters such as newlines in the output and messing up the formatting - These are escaped as special characters in repr.
Finally, note that in my original answer, I define __repr__ but not __str__ and yet the code is still valid - Python is clever enough to fall back to __repr__ when __str__ is not defined, as the full __repr__ will always be more detailed than __str__.
References: Fluent Python, and this excellent SO post: https://stackoverflow.com/questions/1436703/difference-between-str-and-repr