0

我正在用 Python 编写一个非常简单的语言语法的解释器。我有一个超类Statement,它有几个子类。我在超类中有一个CreateStatement评估关键字的方法,并根据找到的关键字创建子类对象的实例。一些子类将需要调用此方法。

我的问题是我收到了这个错误:

AttributeError: 'Statement' object has no attribute 'Assignment'

帮助!

import re
from TokenHandler import TokenHandler
from ParserException import ParserException

class Statement(object):

    tokens = []
    executedTokens = []

    def __init__(self, tokenlist):
        self.tokens = tokenlist

    def getCurrentToken(self):
        print self.tokens[0]
        return self.tokens[0]

    def createStatement(self):
        currenttoken = self.getCurrentToken()

        t = TokenHandler()

        if currenttoken == "print":
            p = Print(self.tokens)
            return p

        elif t.isVariable(currenttoken):
            a = Assignment(self.tokens)
            return a

        elif currenttoken == "if":
            i = IF(self.tokens)
            return i

        elif currenttoken == "while":
            w = While(self.tokens)
            return w

        elif currenttoken == "begin":
            s = self.CompoundStatement(self.tokens)
            return s

        else:
            raise ParserException('Reserved word \'end\' expected')

    #...other methods...

from Statement import Statement
from TokenHandler import TokenHandler
import VariableException

class Assignment(Statement):

    def __init__(self, tokens = []):
        super(Assignment, self).__init__(tokens)

    #...other methods...
4

1 回答 1

2
    a = self.Assignment(self.tokens)

如果Assignment是在模块级别定义的子类而不是Statement类或self实例的属性,则错误。你的意思是

    a = Assignment(self.tokens)

这一行可能同样是错误的:

    s = self.CompoundStatement(self.tokens)
于 2012-04-09T23:45:21.560 回答