1

我很好奇我应该如何实现一个对象的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() 方法吗?我似乎不能只是连接它并让它隐式地将其转换为字符串。

4

2 回答 2

2

你想要repr(b),没有b.reprrepr是一个函数。 __repr__是当您调用该对象时repr在该对象上调用的魔术方法。

于 2013-02-05T06:44:13.663 回答
2

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

object.__repr__(self)[文档]

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
于 2013-02-05T06:49:12.023 回答