-1

I have some 3 layers which are connected by parent - child - sub-child as compositions. Where the child element depends on the upper parent element (and is destroyed when parent is destroyed). Like a book, which has several pages, which has several words. How do i model this correctly? I want to create them from the inside to outside and the best is to add the 2 childs as a list to the respective parent object.

class Book:    
    def __init__(self, bookName):
        self.bookName = bookName
        self.listOfPageObjects = []


class Page(Book):
    pageBackColor = "white"

    def __init__(self, bookName, numberOfWords, pageNumber):
        super().__init__(bookName)
        self.numberOfWords = numberOfWords
        self.pageNumber = pageNumber
        self.listOfWordObjects = []


class Word(Page):
    wordFont = "courier"
    wordMaxLen = 100

    def __init__(self, bookName, numberOfWords, pageNumber, actualWord):
        super().__init__(bookName, numberOfWords, pageNumber)
        self.actualWord = actualWord

Would this be the ideal way to do that?

Dr. Joe
  • 33
  • 4
  • 4
    A page is not a kind of book, nor is a word a kind of page; inheritance is not appropriate here. – chepner Jan 14 '20 at 23:08
  • Instead of inheritance, [maybe a data class](https://stackoverflow.com/questions/47955263/what-are-data-classes-and-how-are-they-different-from-common-classes) decorator would be more appropriate. – PeptideWitch Jan 14 '20 at 23:09

1 Answers1

2

Composition means storing a collection of objects inside another object. A very simple example: a Book is primarily a list of Pages, and a Page is primarily a list of Words.

class Book:
    def __init__(self, name, pages):
        self.book_name = name
        self.pages = pages

class Page:
    def __init__(self, number, words):
        self.number = number
        self.words = words

class Word:
    def __init__(self, word, font="Courier"):
        self.word = word
        self.font = font

pages = [Page(1, [Word("Call"), Word("me"), Word("Ishmael"), ...]),
         Page(2, [...])],
         ...
        ]

b = Book("Moby Dick", pages)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • ok thanks for your all input. It is very helpful. Still 2 questions: - do you see the need not to do this with a list, but with a dict or something else? - can somebody give me a link to an clean coded example python software (learn by reading code) of such a use case? – Dr. Joe Jan 19 '20 at 10:17