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

Question:

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

Asked By: Half Dream

||

Answers:

    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.

Answered By: FLAK-ZOSO
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.