我一直在快速学习 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 以及它究竟是什么意思?为什么第二个例子不起作用?