在python中这个定义是什么样的变量?

2024-09-28 21:13:58 发布

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

我在阅读《机器学习在行动中》一书时遇到了一个问题:
文件名是treePlotter.py,它包含一个函数,用matplotlib从dict中绘制树。createPlot是调用来绘制的函数,plotTree是{}调用的函数,代码如下:

def plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on
    numLeafs = getNumLeafs(myTree)  #this determines the x width of this tree
    depth = getTreeDepth(myTree)
    firstStr = myTree.keys()[0]     #the text label for this node should be this
    print plotTree.xOff;
    cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
    print plotTree.xOff
    plotMidText(cntrPt, parentPt, nodeTxt)
    plotNode(firstStr, cntrPt, parentPt, decisionNode)
    secondDict = myTree[firstStr]
    plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes   
            plotTree(secondDict[key],cntrPt,str(key))        #recursion
        else:   #it's a leaf node print the leaf node
            plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
            plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
            plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
    plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
#if you do get a dictonary you know it's a tree, and the first element will be another dict

def createPlot(inTree):
    fig = plt.figure(1, facecolor='white')
    fig.clf()
    axprops = dict(xticks=[], yticks=[])
    createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)    #no ticks
    #createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses 
    plotTree.totalW = float(getNumLeafs(inTree))
    plotTree.totalD = float(getTreeDepth(inTree))
    plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
    plotTree(inTree, (0.5,1.0), '')
    plt.show()

我无法想象的是:作为一个函数,plotTree有。方法在自身中创建新变量!我曾经研究过C/C++和java,只有类书。把手。
python函数也是类吗?如果是这样,我们甚至可以在类之外创建它的公共变量吗?在


Tags: thekey函数ifthisdictmytreexoff
1条回答
网友
1楼 · 发布于 2024-09-28 21:13:58

Python的函数实际上是对象(function类的实例)。模块和类实际上也是对象。好吧,你能说出的一切都是一个物体。在

现在以这种方式使用函数属性是非常糟糕的做法。。。在

相关问题 更多 >