Python:树增长中构造函数调用的子引用赋值

2024-06-16 14:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个相当具体的问题,但由于我不知道这里发生了什么,让我向您介绍这个问题:

在增长决策树时,我有一个分割节点的函数,也就是说,它将两个子节点附加到一个节点上。由于某些原因,下面的代码将节点本身指定为一个子节点,这样id(currentNode.children[0])==id(当前节点):

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]);

关键部分可能是:

^{pr2}$

根据我的理解,构造函数调用应该返回一个对新创建的节点对象的引用,这绝不能与对父节点的引用相同,因为它是一个新对象。在

节点对象是:

class node:    
    data = None;
    attributes = None;    
    attribute = None;    
    children = [None,None];

    def __init__(self,data,attributes):
        self.data = data;
        self.attributes = attributes;

由于我是Python中的oop新手,而且对oop一般不太熟悉,所以我希望在这方面我有一些误解,但是我不知道如何指定这个问题。谢谢。在


Tags: 对象selfnoneidnodedata节点def
2条回答

嘿,托比亚斯,我是安贾纳。在

这个问题可能是因为在节点类声明(或定义或其他)中,您将数据、属性、属性和子级定义为类级属性吗?这意味着在创建新节点对象时节点.子项值不会更改,对于实例化节点类的任何对象,例如thisnode=Node(),thisnode.children将与所有其他节点对象相同(thisnode.children= 节点.子项)在

如果您希望每个节点对象的值都不同,那么必须在init方法中设置它(比如自己的孩子). 在

不确定这是否与此有关。。。告诉我。在

解决方案:Python OOP不同于javaoop!将类定义更改为:

class node:
def __init__(self,data,attributes):
    self.data = data;
    self.attributes = attributes;
    self.children = [None,None];
    self.attribute = None;

相关问题 更多 >