This is a rather specific question but since I could not figure out what happens here, let me present you the problem:
Growing a decision tree, I have a splitting function that splits a node, that is it attaches two children to a node. For some reason, the code below assigns a node itself as a child such that id(currentNode.children[0])==id(currentNode):
def split(currentNode):
if impure(currentNode.data):
currentNode.attribute = getBestAttr(currentNode.attributes,currentNode.data);
childrenAttributes = deepcopy(currentNode.attributes);
childrenAttributes.remove(currentNode.attribute);
childrenData = splitData(currentNode.data,currentNode.attribute);
for i in range(2):
currentNode.children[i] = node(childrenData[i],childrenAttributes);
split(currentNode.children[i]);
Where the crucial part is probably:
for i in range(2):
currentNode.children[i] = node(childrenData[i],childrenAttributes);
split(currentNode.children[i]);
From my understanding, the constructor call should return a reference to the newly created node object which can in no way be the same as the reference to the parent node, because it is a NEW object.
The node object is:
class node:
data = None;
attributes = None;
attribute = None;
children = [None,None];
def __init__(self,data,attributes):
self.data = data;
self.attributes = attributes;
As I am new to oop in Python and not very experienced in oop in general, I expect that I have some misunderstanding in this respect, but I can’t figure out how to specify the question. Thanks.
Hey Tobias it’s Anjana.
Could the problem have to do with the fact that in the node class declaration (or definition or whatever), you’re defining data, attributes, attribute, and children as class-level attributes? That means when you create a new Node object, the Node.children value will not change, and for any object that instantiates the Node class, e.g. thisnode = Node(), thisnode.children will be the same as for all other node objects (thisnode.children = Node.children)
If you want it to be different for every node object, then you have to set it up it in the init method (like self.children).
Not sure if that has anything to do with it… let me know.