第一次使用类,有助于调试

2024-10-02 14:27:20 发布

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

这是我的帖子代码:这是没有完整的代码,但足以解释我的请不要怀疑丢弃任何你认为不相关的代码行

enter code here
saving_tree={}   
isLeaf=False
class tree:
    global saving_tree
    rootNode=None
    lispTree=None
    def __init__(self,x):
        file=x
        string=file.readlines()
        #print string
        self.lispTree=S_expression(string)
        self.rootNode=BinaryDecisionNode(0,'Root',self.lispTree)

class BinaryDecisionNode:
    global saving_tree     
    def __init__(self,ind,name,lispTree,parent=None):

        self.parent=parent

        nodes=lispTree.getNodes(ind)
        print nodes
        self.isLeaf=(nodes[0]==1)
        nodes=nodes[1]#Nodes are stored
        self.name=name
        self.children=[]
        if self.isLeaf: #Leaf Node
            print nodes
            #Set the leaf data
            self.attribute=nodes
            print "LeafNode is ",nodes
        else:            
            #Set the question
            self.attribute=lispTree.getString(nodes[0])
            self.attribute=self.attribute.split()


            print "Question: ",self.attribute,self.name
            tree={}
            tree={str(self.name):self.attribute}
            saving_tree=tree
            #Add the children
            for i in range(1,len(nodes)):#Since node 0 is a question
               # print "Adding child ",nodes[i]," who has ",len(nodes)-1," siblings"
                self.children.append(BinaryDecisionNode(nodes[i],self.name+str(i),lispTree,self))

        print saving_tree

我想在saving_tree{}中保存一些数据,这是我之前声明的,我想在什么时候上课我要求打印保存树,但仅限于该实例。我希望保存树{}有数据存储所有实例的数据并在外部访问它。 当我要求在类外保存打印树时,它打印空的{}。。 请告诉我所需的修改,以获得所需的输出并在类外使用保存树{}。。你知道吗


Tags: 代码nameselfnonetreestringattributeparent
1条回答
网友
1楼 · 发布于 2024-10-02 14:27:20

saving_tree__init__方法中不是global(与类主体的作用域不同)。您可以通过在方法中添加global saving_tree作为第一个语句来解决这个问题(并在主体中删除不起作用的语句)。你知道吗

更好的方法是忽略global,改用class属性:

class BinaryDecisionTree(object):
    saving_tree = None
    def __init__ ...
        ...
        BinaryDecisionTree.saving_tree = ...

global充其量是一种一般的方法,而转向OOP(面向对象编程,即class语句)的一个优点是它省去了对global的任何需要,因为您可以始终使用类或实例属性。你知道吗

相关问题 更多 >