pythonrepr

Why can __repr__ function use repr() in itself when defining a class?(Python)


class Link:

    def __repr__(self):
        if self.rest is not Link.empty:
            rest_repr = ', ' + repr(self.rest)
        else:
            rest_repr = ''
        return 'Link(' + repr(self.first) + rest_repr + ')'

I wonder :Is the repr function a built-in funciton in Python even though I am defining the __repr__ function?

Answer: the repr() is a bulit-in function. we can use the repr() in the __repr__ function


Solution

  •     def __repr__(self):
            if self.rest is not Link.empty:
                rest_repr = ', ' + repr(self.rest)
    

    Look at this piece of code, what do you notice?

    Exactly: you are using repr(self.rest), which is equivalent to self.rest.__repr__().

    In other words you aren't calling repr on an instance of Link, but just on an attribute of it. So you aren't calling Link.__repr__ into its body, don't worry.