Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

python classes

Name: Anonymous 2010-01-05 23:50

OK, say I need to create an application that simulates a
family tree.  Each member may have a mom dad and kids.

I need to create a family tree class that contains a
collection of these member class objects and methods for
adding branches, removing members, etc...

I'm mainly having a hard time figuring how to join the
members if that makes sense.

I've got something like...

class member(object):
   
    def __init__(self):
       member.kid = self[0]
       member.dad = self[1]
       etc...


class familyTree(object):

    def __init___(self):
        for m in mlist:
            try:
                m = member(m)

blah blah blah


How to I make the familytree class contain a
collection of member class objects?

Name: Anonymous 2010-01-08 4:22

Just for you, OP, even though it probably won't help you much with your family tree application.

This is a tree:

    a
   / \
  b   c
     /|\
    d e f
    |
    g


But notice that this part of it is also a tree:

[/m]  d
  |
  g[/m]

And even g itself is a tree.

As you can see, a tree is just a node with (any number, including 0) children trees (nodes, whatever).

The simplest way would be for each node to only store its children. In Python you could do it like:

class Node(object):
    __slots__ = ['children']
    def __init__(self, *cs):
        self.children = list(cs)

g = Node()
d = Node(g)
e = Node()
f = Node()
c = Node(d,e,f)
b = Node()
a = Node(b,c)


and you could use any of a..g as the root node of a tree.

Now, this is the basic way to represent a tree and you can extend it however you like. You could keep track of the parent node for each node, or add a tag or value field or whatever.
As for a Tree class, you can choose not to make one at all, but essentialy it would be a glorified Node with some additional functionality or built-in checks or whatever (either inheriting from Node or storing an instance of it in a private field).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List