-3

运行以下代码时:

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
4

1 回答 1

4

你不是您没有告诉我们哪一行给了您错误,但我可以看到您的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")
于 2020-11-03T12:59:37.320 回答