سؤال

I'm curious how I should be be implementing the repr method of an object that contains other objects that implement repr.

For example (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

Do I have to directly call that repr() method? i can't seem to just concat it and have it implicitly convert it to a string.

هل كانت مفيدة؟

المحلول

Call the repr() function on the Book instance:

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

نصائح أخرى

You want repr(b), not b.repr. repr is a function. __repr__ is the magic method called on an object when you call repr on that object.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top