How can I define and use a __repr__ method?

Question

How can I define and use a repr method?

Answer

In our class Print3D, there are a few key points to make our __repr__() method useful.
Be sure to pass self to any class method, including __repr__(), like this: def __repr__(self):
Inside we need to define how our object is printed. Whenever the built-in print function receives our object, it looks for a __repr__() method, and if it’s found, it prints the return value to the screen! So we just return what the instructions ask: "(%d, %d, %d)" % (self.x, self.y, self.z)

4 Likes

Did you mean to include “__” after “repr”???

4 Likes

Good catch. Thanks for pointing this out.

3 Likes

See documentation at object. __repr__ ( self ).

Note that the documentation states …

The return value must be a string object.

5 Likes

I read the Python documentation and it didn’t clarify much for me.

What is the usefulness of repr()? How is it different than print?
Does it force non-str() into str() so we do not have to append str() to non-str()?

Are there other uses for it? is it always used in a class (as in the lesson?)

-Thank you-

The difference is between __repr__() and __str__(), not print(), so we’re clear. The latter is less formal and generally applied when we want string output without having to specify attributes. The former is more of an inspection tool that lets us see explicit information relating to the object.

>>> class Foo:
	def __init__(self, foo):
		self.foo = foo
	def __repr__(self):
		return f'{self.__class__.__name__}, foo = {self.foo}'
	def __str__(self):
		return f'{self.foo}'

	
>>> bar = Foo('bar')
>>> bar
Foo, foo = bar
>>> print (bar)
bar
>>> 

Perhaps this article will help…

https://dbader.org/blog/python-repr-vs-str

I feel I’ve done everything right, however, I keep getting the error below. What’s the issue?

Compare your output to the error message? Notice the brackets?

Ahh yes, the parentheses. The exercise wants the parentheses printed as well. Figured that out shortly after posting this. :sweat_smile:

1 Like

Following codes are no error message:
class Point3D(object):

def init(self, x, y, z):

self.x = x

self.y = y

self.z = z

def repr(self):

return "(%d, %d, %d)" %(self.x, self.y, self.z)

my_point = Point3D(self, self.x, self.y, self.z)

my_point = Point3D(1, 2, 3)

print my_point