0

I've been learning Python rapidly and am getting confused with the representational form and string form of an object as well as the repr method. I call x = Point(1, 3) with the following code and get:

class Point():
def __init__(self, x, y):
    '''Initilizae the object'''
    self.x = x
    self.y = y
def __repr__(self):
    return "Point({0.x!r}, {0.y!r})".format(self)
def distance_from_origin(self):
    return math.hypot(self.x, self.y)
>>>x
Point(1, 3)

If !r conversion field is for representing the variable in a string that can be evaluated by Python to create another identical object using eval() statement, why doesn't this work:

class Point():
    def __init__(self, x, y):
        '''Initilizae the object'''
        self.x = x
        self.y = y
    def __repr__(self):
        return "{!r}".format(self)
    def distance_from_origin(self):
        return math.hypot(self.x, self.y)
>>>x
File "C:\...\...\examplepoint.py, line 8, in __repr__
   return "{!r}".format(self)
File "C:\...\...\examplepoint.py, line 8, in __repr__
   return "{!r}".format(self)
File "C:\...\...\examplepoint.py, line 8, in __repr__
   return "{!r}".format(self)
File "C:\...\...\examplepoint.py, line 8, in __repr__
   return "{!r}".format(self)
The same error for 100 more lines
RuntimeError: maximum recursion depth exceeded

I thought that the !r specification would create object x type Point into a string in representation form that would look like: Point(1, 3) or similar to the first run. How exactly does Python do this representation !r in string format and what exactly does it mean? Why doesn't the second example work?

1

1 Answer 1

3

!r calls repr() (which calls __repr__ internally) on the object to get a string. It makes no sense to ask for the representation of an object in the definition of its __repr__. That's recursive, which is what the traceback tells you. There is no requirement that the representation of the object has to to be evaluable, and Python does not create this sort of representation for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.