使用Python和__repr__打印嵌套对象

1 投票
2 回答
2677 浏览
提问于 2025-04-17 14:47

我很好奇,当一个对象里面包含其他实现了repr方法的对象时,我应该怎么写这个repr方法。

举个例子(像Python那样):

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 个回答

2

你需要用 repr(b),而不是 b.repr。这里的 repr 是一个函数。而 __repr__ 是一个特殊的方法,当你对一个对象使用 repr 时,这个方法会被调用。

2

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

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

撰写回答