python - 为什么我会收到 "instance has no attribute ' __getitem_ _' "错误?

标签 python

代码如下:

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.left = None
        self.right = None
        root = [self.key, self.left, self.right]

    def getRootVal(root):
        return root[0]

    def setRootVal(newVal):
        root[0] = newVal

    def getLeftChild(root):
        return root[1]

    def getRightChild(root):
        return root[2]

    def insertLeft(self,newNode):
        if self.left == None:
                self.left = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.left = self.left
            self.left = t

    def insertRight(self,newNode):
        if self.right == None:
            self.right = BinaryTree(newNode)
        else:
            t = BinaryTree(newNode)
            t.right = self.right
            self.right = t

def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in '+-*/)':
            currentTree.setRootVal(eval(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in '+-*/':
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            print "error:  I don't recognize " + i
    return eTree

def postorder(tree):
    if tree != None:
        postorder(tree.getLeftChild())
        postorder(tree.getRightChild())
        print tree.getRootVal()

def preorder(self):
    print self.key
    if self.left:
        self.left.preorder()
    if self.right:
        self.right.preorder()

def inorder(tree):
    if tree != None:
        inorder(tree.getLeftChild())
        print tree.getRootVal()
        inorder(tree.getRightChild())

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

def main():
    parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " )
    tree = buildParseTree(parseData)
    print( "The post order is: ", + postorder(tree))
    print( "The post order is: ", + postorder(tree))
    print( "The post order is: ", + preorder(tree))
    print( "The post order is: ", + inorder(tree))

main()

这里是错误:

Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 )
Traceback (most recent call last):
  File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in 
    main()
  File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main
    tree = buildParseTree(parseData)
  File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree
    currentTree = currentTree.getLeftChild()
  File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild
    return root[1]
AttributeError: BinaryTree instance has no attribute '__getitem__'

最佳答案

因为你声明你的方法是错误的:

让我们看看调用 tree.getRootVal() 会发生什么。 .getRootVal() 是这样声明的:

def getRootVal(root):
    return root[0]

您可能知道,传递给方法的第一个参数始终是实例,并且它是隐式提供的。因此,您基本上尝试将 BinaryTree 的实例视为一个序列 (root[0])。

你必须这样指定它:

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.left = None
        self.right = None
        self.root = [self.key, self.left, self.right]   # self.root

    def getRootVal(self):
        return self.root[0]   # access self.root

    def setRootVal(self, newVal):
        self.root[0] = newVal

    # and also the other functions

对象方法的第一个参数不必称为self。但这样做有助于避免像您那样的错误。

有趣的是,您正确地声明了 insertLeftinsertRight ;)

关于python - 为什么我会收到 "instance has no attribute ' __getitem_ _' "错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541718/

相关文章:

Python:汇总和聚合 DataFrame 中的组和子组

python - 使用 latex 编码时如何在绘图轴标签中引入换行符?

python - 针对曝光不足或过度的照片进行 SimpleCV 色彩校正

python - 在Python中使用多重处理处理大文件: How to load resources only once per process?

Python groupby错误, 'unhashable'系列对象

python - 选择不等于零的不同 pandas 行中的最小值

python - 使用 `pandas.cut()` ,我如何获得整数分箱并避免获得负的最低限度?

javascript - Python 到 JavaScript 持久连接

python - 从 python 和 launchd 启动 osascript

python - 在 Flask 微框架中使用 WTForms 的 populate_obj( ) 方法