使用python和__repr__打印嵌套对象

时间:2013-02-05 06:36:44

标签: python repr

我很好奇我应该如何实现包含实现 repr 的其他对象的对象的 repr 方法。

例如(pythonish):

class Book():
    def__repr__
        return 'author ... isbn'

class Library(): 
    def __repr__:
        me ='['
        for b in books:
            me = me + b.repr()
        me = me + ']'
        return me

我是否必须直接调用该repr()方法?我似乎无法将它连接起来并将其隐式转换为字符串。

2 个答案:

答案 0 :(得分:2)

您需要repr(b),而不是b.reprrepr是一个功能。当您在该对象上调用__repr__时,repr是在对象上调用的神奇方法。

答案 1 :(得分:1)

调用repr()实例上的Book函数:

object.__repr__(self) [docs]

Called by the repr() built-in function and by string conversions (reverse quotes)
to compute the “official” string representation of an object. [...] The return 
value must be a string object. If a class defines __repr__() but not __str__(),
then __repr__() is also used when an “informal” string representation of 
instances of that class is required.

class Book(object):    
    def __repr__(self):
        return 'I am a book'

class Library(object):    
    def __init__(self,*books):
        self.books = books
    def __repr__(self):
        return ' | '.join(repr(book) for book in self.books)

b1, b2 = Book(), Book()
print Library(b1,b2)

#prints I am a book | I am a book