-2

When running the following code:

class Book:
    def __init__(self, isbn, title, author, publisher, pages, price, copies):
        self.isbn = isbn
        self.title = title
        self.author = author
        self.publisher = publisher
        self.pages = pages
        self.price = price
        self.copies = copies

    def display(self):
        print("==" * 15)
        print(f"ISBN:{self.isbn}")
        print(f"Title:{self.title}")
        print(f"Author:{self.author}")
        print(f"Copies:{self.copies}")
        print("==" * 15)

    def in_stock(self):
        if self.copies > 0:
            return True
        else:
            return False

    def sell(self,):
        if self.copies > 0:
            self.copies -= 1
        else:
            print("Out of Stock")

    @property
    def price(self):
        return self.price

    @price.setter
    def price(self, new_price):
        if 50 < new_price < 500:
            self.price = new_price
        else:
            raise ValueError("Invalid Price")


book1 = Book("957-4-36-547417-1", "Learn Physics", "Professor", "sergio", 350, 200, 10)
book2 = Book("652-6-86-748413-3", "Learn Chemistry", "Tokyo", "cbc", 400, 220, 20)
book3 = Book("957-7-39-347216-2", "Learn Maths", "Berlin", "xyz", 500, 300, 5)
book4 = Book("957-7-39-347216-2", "Learn Biology", "Professor", "sergio", 400, 200, 0)

books = [book1, book2, book3, book4]
for book in books:
    book.display()

Professor_books = [Book.title for Book in books if Book.author == "Professor"]
print(Professor_books)

I get the following infinite recursion error:

Traceback (most recent call last):
  File "test.py", line 43, in <module>
    book1 = Book("957-4-36-547417-1", "Learn Physics", "Professor", "sergio", 350, 200, 10)
  File "test.py", line 8, in __init__
    self.price = price
  File "test.py", line 38, in price
    self.price = new_price
  File "test.py", line 38, in price
    self.price = new_price
  File "test.py", line 38, in price
    self.price = new_price
  [Previous line repeated 993 more times]
  File "test.py", line 37, in price
    if 50 < new_price < 500:
RecursionError: maximum recursion depth exceeded in comparison
Aplet123
  • 33,825
  • 1
  • 29
  • 55

1 Answers1

4

You're not You were not telling us which line is giving you the error, but I can see that your price property setter is assigning to self.price, which will lead to infinite recursion as it also calls the setter, etc.

You will need a non-property backing field for the price - commonly one tends to prefix such a name with an underscore (self._price):

    @property
    def price(self):
        return self._price

    @price.setter
    def price(self, new_price):
        if 50 < new_price < 500:
            self._price = new_price
        else:
            raise ValueError("Invalid Price")
AKX
  • 152,115
  • 15
  • 115
  • 172