开发者

Using classes for the first time,help in debugging

here is post my code:this is no the entire code but enough to explain my doubt.please discard any code line which u find irrelavent

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

i wanted to save s开发者_StackOverflowome data in saving_tree{},which i have declared previously and want to use that saving tree in the another function outside the class.when i asked to print saving_tree it printing but,only for that instance.i want the saving_tree{} to have the data to store data of all instance and access it outside. when i asked for print saving_tree outside the class it prints empty{}.. please tell me the required modification to get my required output and use saving_tree{} outside the class..


saving_tree is not global in the __init__ method (which is a different scope than the class body). You could fix that by adding global saving_tree as the first statement in the method (and remove that in the body which plays no role).

A better approach would be to forget about global and use a class attribute instead:

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

globals are always, at best, a so-so approach, and one of the advantages of moving to OOP (object oriented programming, i.e., class statements) is that it saves any need for global as you can always use class or instance attributes instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜