根据Python中的关键字创建对象并调用其方法

时间:2012-04-09 23:42:55

标签: python

我正在用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...

1 个答案:

答案 0 :(得分:2)

    a = self.Assignment(self.tokens)
如果Assignment是在模块级别定义的子类而不是Statement类或self实例的属性,则

是错误的。你的意思是

    a = Assignment(self.tokens)

这一行可能同样错误:

    s = self.CompoundStatement(self.tokens)