Write a class definition named Book. The Book class should have data attributes for a book’s title, the author’s name, and the publisher’s name. The class should also have the following:
An _ init _ method for the class. The method should accept an argument for each of the data attributes.
Accessor and mutator methods for each data attribute.
An _ str _ method that returns a string indicating the state of the object.
Below I’ve attatched my code. Anytime I try running it, I’m getting nothing. Can anyone tell me what I’m doing wrong? Thanks!:
class Book:
# Initializer
def __init__(self,title,author,publisher):
self.__title = title
self.__authr = author
self.__publr = publisher
# Mutators
def set_title(self,title):
self.__title = title
def set_author(self,author):
self.__authr = author
def set_publr(self,publisher):
self.__publr = publisher
# Accessors
def get_title(self):
return self.__title
def get_author(self):
return self.__authr
def get_publr(self):
return self.__publr
# _str_method
def __str__(self):
book = Book (title=None,author=None, publisher=None)
book.set_title('Ends with us')
book.set_author('Colleen Hoover')
book.set_publr('Simon & Schuster')
return("Book's Title:", + self.__title + \
"\nAuthor:", + str(self.__authr) + \
"\nPublisher: $", + str(self.__publr))
>Solution :
The issue with your code seems to be with the implementation of the str method. Here are a few changes you can make to fix it:
Remove the lines where you create a new Book object and set its attributes. Instead, you should be returning the values of the attributes of the current Book object.
Remove the commas after the string literals in the return statement. These commas will cause a syntax error.
Instead of concatenating strings with +, use f-strings to format the string with the values of the object’s attributes.
def __str__(self):
return f"Book's Title: {self.__title}\nAuthor: {self.__author}\nPublisher: {self.__publisher}"
Now you can create the object for this:
book1 = Book("Ends with Us", "Colleen Hoover", "Simon & Schuster")
print(book1)