HanSooloo
HanSooloo

Reputation: 763

How to create a Python object that represents a simple hierarchy of self-typed children

I have a simple class in mind, called Page. Page has an ID and a Title. Page can also have child Page's stored in the Page's children attribute.

I thought about doing this:


class Page:
  def __init__(self, id: int, title: str):
    self.id = id
    self.title = title
    self.children = list[Page]

  def add_child(self, child: Page):  # Python doesn't like type hint of "Page"
    self.children.append(child)

2 questions:

  1. Do I have the children attribute done right? It is supposed to be a list of other Page's.
  2. How can I provide the proper type hint in add_child?

Would love to learn if there are other suggestions for this kind of pattern.

EDIT: Currently, add_child gives the following error:

TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'Page' object

Upvotes: 0

Views: 30

Answers (0)

Related Questions