Я нашел эту ошибку рекурсии. Я не мог понять, где проблема

При запуске следующего кода:

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)

Я получаю следующую ошибку бесконечной рекурсии:

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

person Sibasis Malla    schedule 03.11.2020    source источник
comment
Какую ошибку вы получили?   -  person expressjs123    schedule 03.11.2020
comment
ошибка рекурсии   -  person Sibasis Malla    schedule 03.11.2020
comment
Дубликат: stackoverflow.com/questions/36931415/   -  person Tomerikoo    schedule 03.11.2020


Ответы (1)


Вы нет Вы не сказали нам, какая строка выдает ошибку, но я вижу, что ваш установщик свойства price присваивает значение self.price, что приведет к бесконечной рекурсии, поскольку он также вызывает установщик , так далее.

Вам понадобится поле поддержки, не являющееся свойством, для цены - обычно к такому имени обычно добавляют префикс подчеркивания (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")
person AKX    schedule 03.11.2020
comment
Спасибо Гоча! - person Sibasis Malla; 03.11.2020