views:

199

answers:

3

Hello,

i am trying to read a tree structure file in python. I created a class to hold the tree objects. One of the members should hold the parent object. Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self".

How do I do that in python?

Thank you very much for your help.

+6  A: 

In Python, you don't declare variables as having any type. You just assign to them. A single variable can be assigned objects of different types in succession, if you wanted to do so. "self" is not the type but a naming convention used to refer to the current object, like "this" in Java / C++ (except in Python you could call it anything you wanted).

danben
+1  A: 

I assume that for the root node, you want such an object. It's much more Pythonic to say:

self.parent = None

in your root object, than to create an empty object of type self.__class__. For every other node object in the tree, self.parent should refer to the actual parent node.

Remember, in Python you don't have 'variables', you have objects, and there is no need for self.parent to be of same type in all the instances of a class.

Alok
+2  A: 

Since the parentObject member is of the same type as the class itself, I need to declare this as an empty variable of type "self".

No, you do not need to declare anything in Python. You just define things.

And self is not a type, but the conventional name for the first parameter of instance methods, which is set by the language to the object of the method.

Here's an example:

class Tree(object):

    def __init__(self, label=None):
        self.label = label
        self.parent = None
        self.children = []

    def append(self, node):
        self.children.append(node)
        node.parent = self

And here's how that could be used:

empty_tree = Tree()

simple_tree = Tree()
simple_tree.append(Tree('hello'))
simple_tree.append(Tree('world'))
ddaa