Home > other >  Why is the following code outputting [<__main__.Book object at 0x00000207911F1FD0>]. While I e
Why is the following code outputting [<__main__.Book object at 0x00000207911F1FD0>]. While I e

Time:10-25

This is a fairly simple code that adds books and their info to the list. Yet I recieve unexpected output.

class Book:
    def __init__(self, name, author, code):
        self.name = name
        self.author = author
        self.code = code
        self.available = True

class Library:
    def __init__(self):
        self.books = []

    def addBook(self, book):
        self.books.append(book)


algebra = Book('Algebra for beginners', 'Albert Einstein', 123)
lib = Library()

lib.addBook(algebra)
print(lib.books)

CodePudding user response:

Because the type is Book followed by its identifier. If you want something human readable use __repr__ (str representation)

Try

class Book:
    def __init__(self, name, author, code):
        self.name = name
        self.author = author
        self.code = code
        self.available = True

    def __repr__(self):
        return f"<{self.__class__.__name__} ({self.name} by {self.author})>"

class Library:
    def __init__(self):
        self.books = []

    def addBook(self, book):
        self.books.append(book)


algebra = Book('Algebra for beginners', 'Albert Einstein', 123)
lib = Library()

lib.addBook(algebra)
print(lib.books)

CodePudding user response:

there are two ways to go here:

Method 1 - asForceBru suggests in the comment, add a __repr__ method to the Book class, which returns a string:

class Book:
    def __init__(self, name, author, code):
        self.name = name
        self.author = author
        self.code = code
        self.available = True
    def __repr__(self):
        return self.name ", " self.author ", code: " \
            str(self.code) ", available: " str(self.available) 

so that the output of print(lib.books) is:

[Algebra for beginners, Albert Einstein, code: 123, available: True]

OR

Method 2 - add a __str__ method to both Book and Library classes:

class Book:
    def __init__(self, name, author, code):
        self.name = name
        self.author = author
        self.code = code
        self.available = True
    def __str__(self):
        return self.name ", " self.author ", code: " \
            str(self.code) ", available: " str(self.available)

class Library:
    def __init__(self):
        self.books = []
    def __str__(self):
        info_string = ""
        for b in self.books:
            info_string  = str(b) "\n"
        return info_string
    def addBook(self, book):
        self.books.append(book)

so that now the output of print(lib) is:

Algebra for beginners, Albert Einstein, code: 123, available: True

As you see, the call to print() and output is slightly different.

  • Related