How can I define and use a __repr__ method?


#1

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)


FAQ: Learn Python - Classes - Building useful classes