0

私は Learn Python the Hard Way の演習 48 に取り組んでおり、nosetests を使用してタプルをテストしています。私が設定したノーズテストは次のとおりです。

def test_directions():
    assert_equal(lexicon.scan("north"), [('direction', 'north')])

ただし、毎回次のエラーが発生します。

...line 5, in test_directions
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
TypeError: unbound method scan() must be called with lexicon instance 
as first argument (got str instance instead)

「def scan(self):」のすぐ上に @staticmethod を導入すると、代わりに次のエラーが発生します。

line 24, in scan
    words = self.sentence.split()
AttributeError: 'str' object has no attribute 'sentence'

そして、私がテストしているコードは以下のとおりです。私は何が欠けていますか?

class lexicon(object):

    def __init__(self, sentence):

        self.sentence = sentence

        self.direction = "direction"
        self.verb = "verb"
        self.noun = "noun"
        self.stop = "stop"
        self.number = "number"

        self.direction_words = ('north', 'south', 'east', 'west', 'up', 'down')
        self.verb_words = ('go', 'stop', 'kill', 'eat')
        self.noun_words = ('door', 'bear', 'princess', 'cabinet')
        self.stop_words = ('the', 'in', 'of', 'from', 'at', 'it')

        self.a = 0
        self.instructions = []

    def scan(self):

        words = self.sentence.split()
        self.a = 0

        while self.a < len(words):
            result = words[self.a]
            if result in self.direction_words:
                self.instructions.append(('direction', result))
            elif result in self.verb_words:
                self.instructions.append(('verb', result))
            elif result in self.noun_words:
                self.instructions.append(('noun', result))
            elif result in self.stop_words:
                self.instructions.append(('stop', result))
            elif self.test_num(result) == None:
                self.instructions.append(('number', "Error"))
            else:
                self.instructions.append(('number', result))
            self.a += 1

        return self.instructions

    def test_num(self, num):
        try:
            return int(num)
        except ValueError:
            return None
4

2 に答える 2

3

最初にレキシコン オブジェクトを文字列でインスタンス化してから、そのオブジェクトで scan を呼び出す必要があるようです。要するに:

def test_directions():
    assert_equal(lexicon("north").scan(), [('direction', 'north')])

これは、__init__メソッドがsentence引数として取るのに対し、scanメソッドには実際の引数がない (selfオブジェクトのインスタンスを表す のみ) ためです。justを使用@staticmethodすると、文 (この場合は "north") がクラスのインスタンスとして扱われ、lexicon明らかな理由で失敗します。

于 2012-07-12T06:57:06.133 に答える