Why is `print(object)` displaying “?

When you just print an object, it shows the object id (like <__main__.Camera object at 0x02C08790>), which is totally indecipherable to us mortals. You can get around this by defining a __str__ or __repr__ function to display the data for the instance in a custom way.

In your case:

def __repr__(self):
    return "<__main__.Camera: distance = " + str(self.distance) + "; speed_limit = " + str(self.speed_limit) + "; number_of_cars = " + str(self.number_of_cars) + ">"

If there were an instance of Camera with the starting variable values, it would return

"<__main__.Camera: distance = 2; speed_limit = 20; number_of_cars = 0>".

The <__main__.Camera object at 0x02C08790> is the how the system remembers it, but aside from showing what type of object it is, it’s mostly useless.

Leave a Comment