【问题标题】:I found this recursion error. I couldn't wnderstand where is the problen [closed]我发现了这个递归错误。我不知道问题在哪里[关闭]
【发布时间】:2020-11-03 12:56:30
【问题描述】:

运行以下代码时:

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

【问题讨论】:

标签: python python-3.x python-3.9


【解决方案1】:

你不是你没有告诉我们哪一行给你错误,但我可以看到你的price属性设置器正在分配给self.price,这将导致无限递归,因为它也调用 setter 等。

您将需要一个非属性支持字段作为价格 - 通常会在这样的名称前加上下划线 (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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多