字符串格式化python中的表示形式

时间:2015-01-23 04:58:43

标签: python string format repr

我一直在快速学习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规范会将对象x类型Point创建为表示形式的字符串,如下所示:Point(1,3)或类似于第一次运行。 Python究竟如何表达这种表示形式!r是字符串格式,它究竟是什么意思?为什么第二个例子不起作用?

1 个答案:

答案 0 :(得分:2)

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