Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding an object to a list Python OOP

I’m new to python OOP. I’m trying to create a method that gets user’s input (book name, author and genre), creates a book Object and adds it to a list only if such a book doesn’t exist. Initially, I wanted to use __eq__ but couldn’t find a way to make it work…

Here my code:

class Book:
def __init__(self, book_name, author_name, genre):
    self.book_name = book_name
    self.author_name = author_name
    self.genre = genre
    self.booksList=[]

def __eq__(self, other):
    if (self.book_name == other.book_name):
        return True
    else: 
        return False
    
def __str__(self):
    return f"The book {self.book_name} written by {self.author_name} is {self.genre}"

def addBook(self, book_name, author_name, genre):
    if book_name not in self.booksList:
      self.booksList.append(book_name)
      print("success")
    else:
        print("Book already exists")
while True:
    option=input("choose an operation:\n \n") 
    
    if option not in ['1','2','3','4','5','6','7','8']:
            print("Please enter a valid operation")

    if (option=="1"):
                  book_name=input ('Enter book name:')
                  author_name = input ('Enter author name:')
                  genre= input ('Enter genre:')
                  new_book=Book(book_name, author_name, genre)
                  new_book.addBook(book_name, author_name, genre)
              
            #option2  
    elif (option=="2"):
                  pass```

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You tried to add a book to the list of the instance itself.
A simple solution with dunder methods would be the following:

class Book:
    def __init__(self, book_name, author_name, genre):
        self.book_name = book_name
        self.author_name = author_name
        self.genre = genre
        

    def __eq__(self, other):
        if (self.book_name == other.book_name):
            return True
        else: 
            return False
        
    def __str__(self):
        return f"The book {self.book_name} written by {self.author_name} is {self.genre}"

books = []
while True:
    option=input("[-] Choose an operation:\n") 
    
    if option not in ['1','2','3','4','5','6','7','8']:
            print("Please enter a valid operation")

    if option == "1":

                book_name=input ('Enter book name:')
                author_name = input ('Enter author name:')
                genre= input ('Enter genre:')
                new_book=Book(book_name, author_name, genre)
                
                if len(books) > 0:
                    for i, book in enumerate(books):
                        if new_book == book:
                            break
                        else:
                            if i == len(books)-1:
                                books.append(new_book)
                else:
                    books.append(new_book)



            
    elif option == "2":
        for e in books:
            print(e)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading