python没有识别类中的方法

时间:2015-01-01 14:22:35

标签: python

在编写下面的代码并运行它之后,它会给出Name错误:name' parse_sentence'没有定义 请关于问题是什么的任何帮助,或者是否应该把所有其他方法的map方法作为一个类 - 平均值parse_sentence()?

class ParserError(Exception):
    pass

class Sentence(object):

    def __init__(self, subject, verb, obj):
        # remember we take ('noun','princess') tuples and convert them
        self.subject = subject[1]
        self.verb = verb[1]
        self.object = obj[1]

    def peek(word_list):
        if word_list:
            word = word_list[0]
            return word[0]
        else:
            return None

    def match(word_list, expecting):
        if word_list:
            word = word_list.pop(0)

            if word[0] == expecting:
                return word
            else:
                return None
        else:
            return None

    def skip(word_list, word_type):
        while peek(word_list) == word_type:
            match(word_list, word_type)

    def parse_verb(word_list):
        skip(word_list, 'stop')

        if peek(word_list) == 'verb':
            return match(word_list, 'verb')
        else:
            raise ParserError("Expected a verb next.")

    def parse_object(word_list):
        skip(word_list, 'stop')
        next_word = peek(word_list)

        if next_word == 'noun':
            return match(word_list, 'noun')
        elif next_word == 'direction':
            return match(word_list, 'direction')
        else:
            raise ParserError("Expected a noun or direction next.")

    def parse_subject(word_list):
        skip(word_list, 'stop')
        next_word = peek(word_list)

        if next_word == 'noun':
            return match(word_list, 'noun')
        elif next_word == 'verb':
            return ('noun', 'player')
        else:
            raise ParserError("Expected a verb next.")

    def parse_sentence(word_list):
        subj = parse_subject(word_list)
        verb = parse_verb(word_list)
        obj = parse_object(word_list)

        return Sentence(subj, verb, obj)

2 个答案:

答案 0 :(得分:1)

你需要:

  • 将您的所有方法标记为@staticmethod,或者让它们接受self参数。
  • 使用类名或self限定所有方法调用(取决于方法是否为静态)。

例如

def skip(word_list, word_type):
    while peek(word_list) == word_type:
        match(word_list, word_type)

应该是

def skip(self, word_list, word_type):
    while self.peek(word_list) == word_type:
        self.match(word_list, word_type)

@staticmethod
def skip(word_list, word_type):
    while Sentence.peek(word_list) == word_type:
        Sentence.match(word_list, word_type)

答案 1 :(得分:0)

parse_sentenceSentence类的方法。你必须把它称为

Sentence.parse_sentence(...)

(如果它是类方法)或首先创建Sentence的实例:

Sentence(...).parse_sentence(...)