Python Object-Oriented Python Dice Roller Giving a Hand

Can somebody explain the special method __repr__?

Kenneth explains that by using:

def __repr__(self):
        return str(self.value)

we know what values we are getting whenever we call our instance.

I checked on the console and in fact, if I remove the repr I get back a list of objects spitted out whenever I call the instance. But if I use it , I get back a list of ints. Why are we getting back ints if we converted self.value to a string? How does the repr work?

1 Answer

Cooper Runstein
Cooper Runstein
11,818 Points

repr and str are very similar in their purpose, however I learned (And this isn't by any means the only way to do it) that repr should be a representation of how the class is made. So for example:

class Value:
  def __init__(self, value):
    self.value = value

  def __str__(self):
    return str(self.value)

  def __repr__(self):
    return 'Value({})'.format(self.value)

The point of repr is to give representation to your object so when you or another developer checks it out in the console you're not just seeing a memory location.

I'd also take a guess that you're seeing a string that just looks like an int in the console when you inspect the object, but if not, something weird is going on.

Lastly, Python has some default behaviors that you should know about, if you create a class and only give it a repr, you can still use the str() method on your class, python looks for the repr if str doesn't exist. That brings me to your question of how repr works, all the dunder methods have "under the hood" behaviors that python uses, and I have no clue exactly how they all work, nor do I need to, and you probably don't either. What you should know is that python uses repr to replace the default memory location representation of your object with a representation of your object you give it.

Cooper Runstein
Cooper Runstein
11,818 Points

Also I realize Kenneth doesn't follow the same form with repr vs str, but if you change your repr to be something other than just a value you might understand it a bit better.

I played around with the repr to give my objects a different representation just like you advised, and indeed I understood it better. Thank you!