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)
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
>>>