gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:08 24 4
gpt4 key购买 nike

我在阅读机器学习实战这本书时遇到了一个问题:
文件名为 treePlotter.py,它包含一个函数,可以使用 matplotlib 从字典中绘制一棵树。 createPlot是绘制时调用的函数,plotTreecreatePlot调用的函数,代码如下:

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,只有 Classes 有 .处理。
python的函数也是一种类吗?如果是这样,我们甚至可以在类外创建它的公共(public)变量吗?

最佳答案

Python 的函数确实是对象(function 类的实例)。模块和类实际上也是对象。好吧,你能命名的一切都是一个对象。

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

关于python - 在python中这个定义是什么样的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22378606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com