![]() |
programming of compositions (UML) example: forest - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: programming of compositions (UML) example: forest (/thread-17007.html) |
programming of compositions (UML) example: forest - obelix - Mar-24-2019 Hi all, I'd like to code down a correct structured example of some UML class compositions. For now I suggest to use a "Forest" as example. But I am struggling how de correct class designs have to be. Master class: Forest : exists 1 time Children class 1: tree(s) : exists n times below Children class 2 which is below class 1: Branch(es) : exists n times [Forest]<>----[Tree]<>----[Branch] So we have 3 different classes and all depend from its upper class. When upper class is destroyed, the children die. My first question: do I need to design a "class in class" modell? RE: programming of compositions (UML) example: forest - Yoriz - Mar-24-2019 class Branch: pass class Tree: def __init__(self, branches): self.branches = branches class Forest: def __init__(self, trees): self.trees = trees tree1 = Tree([Branch(), Branch()]) tree2 = Tree([Branch(), Branch()]) forest = Forest([tree1, tree2]) RE: programming of compositions (UML) example: forest - obelix - Mar-24-2019 Thanks ! OK, it means i put a list in the arguments of that class instances. But what, when I dont know the number of trees resp. branches? I 'd like to have a addTree resp. addBranch method in the classes. Not sure if this is the correct way ![]() RE: programming of compositions (UML) example: forest - Yoriz - Mar-24-2019 Yes just add a method to add items for example class Tree: def __init__(self, branches=None): self.branches = branches or [] def add_branch(self, branch): self.branches.append(branch) |