2

Here is what I would like to achieve. I am trying to read a tree (let's say a folder structure). I would like to define a generic node in this tree and the initialization of this object should trigger the tree traversing like below

class node():
    def __init__(self, name, parent, children=[]):
        self.name = name
        self.parent = parent
        self.children = children

        nodes = "code to find children"

        for child in nodes:
            children.append(node(childname, self.name))

def main():
    Tree = node("root", "")

When this initial object is initialized it should contain the complete tree. This is for python. Would this work?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MiniMe
  • 1,057
  • 4
  • 22
  • 47

1 Answers1

4

Yes, you can reference the class in the __init__ method, and you can use it to create more instances of the same class. Your approach works.

Do be careful with the children=[] default argument; that will create a shared list, stored once for that method. See "Least Astonishment" and the Mutable Default Argument for why that is going to trip you up and how to avoid that issue.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thanks a lot guys, and I am sorry for the mistakes in the initial post. I am not a programmer... :-) I am learning this art. – MiniMe Feb 01 '16 at 18:59