Python Forum
programming of compositions (UML) example: forest
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
programming of compositions (UML) example: forest
#1
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?
Reply
#2
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])
Reply
#3
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 Confused
Reply
#4
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)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020