0

我一直在快速学习 Python,并且对对象的表示形式和字符串形式以及repr方法感到困惑。我用以下代码调用 x = Point(1, 3) 并得到:

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)

如果 !r 转换字段用于表示可以由 Python 评估以使用 eval() 语句创建另一个相同对象的字符串中的变量,为什么这不起作用:

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

我认为 !r 规范会将 object x type Point 创建为表示形式的字符串,看起来像:Point(1, 3) 或类似于第一次运行。Python 究竟是如何以字符串格式进行这种表示的 !r 以及它究竟是什么意思?为什么第二个例子不起作用?

4

1 回答 1

3

!r在对象上调用repr()__repr__内部调用)以获取字符串。在它的定义中要求一个对象的表示是没有意义的__repr__。这是递归的,这就是回溯告诉你的。不要求对象的表示必须是可评估的,Python 不会为您创建这种表示。

于 2015-01-23T05:48:09.420 回答