在編碼程序中,我遇到了這個簡單的遞回問題,并在下面撰寫了我的代碼示例。我請某人找到解決問題的好方法。我想它應該寫包含關系的第三類。
from __future__ import annotations
from typing import Set
class Author:
def __init__(self):
self.books: Set[Book] = set()
def add_book(self, book: Book):
self.books.add(book)
book.add_author(self)
class Book:
def __init__(self):
self.authors: Set[Author] = set()
def add_author(self, author: Author):
self.authors.add(author)
author.add_book(self)
author = Author()
book = Book()
author.add_book(book) #RecursionError: maximum recursion depth exceeded while calling a Python object
uj5u.com熱心網友回復:
和方法互相呼叫,所以你進入了一個無限回圈add_book()。add_author()
這些方法應該檢查它們是否已經被添加并且不做任何事情,這將停止遞回。
class Author:
def __init__(self):
self.books: Set[Book] = set()
def add_book(self, book: Book):
if book not in self.books:
self.books.add(book)
book.add_author(self)
class Book:
def __init__(self):
self.authors: Set[Author] = set()
def add_author(self, author: Author):
if author not in self.authors:
self.authors.add(author)
author.add_book(self)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496376.html
上一篇:將二叉樹展平為鏈表的遞回解決方案
