3
direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
verbs     = ['go', 'stop', 'kill', 'eat']
stop      = ['the', 'in', 'of', 'from', 'at', 'it']
nouns     = ['door', 'bear', 'princess', 'cabinet']
numbers   = [i for i in range(10)]


class lexicon(object):

    def scan(self, sentence):
        self.sentence = sentence
        self.words    = sentence.split()
        for word in self.words:
            if word is direction:
                word = ('direction','%s' % word)

            return word

http://learnpythonthehardway.org/book/ex48.html是我正在做的,我不知道为什么我的程序没有通过测试。当我运行鼻子测试时,我得到了这个错误。

ERROR: tests.ex48_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/tplaw/Public/projects/installs/venv/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/Users/tplaw/Public/projects/ex48/tests/ex48_tests.py", line 6, 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)

----------------------------------------------------------------------
Ran 1 test in 0.005s

FAILED (errors=1)

我只把测试的第一个部分放在我的测试目录中。它是这个:

from nose.tools import *
from ex48 import lexicon

def test_directions():
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
    result = lexicon.scan("north south east")
    assert_equal(result, [('direction', 'north'),
                          ('direction', 'south'),
                          ('direction', 'east')])
4

2 回答 2

5
lexicon.scan

实例方法,而不是静态方法。你必须构造一个lexicon,然后调用scan它。

lex = lexicon() # This will create an instance of the lexicon class
lex.scan() # This will invoke the instance method of the instantiated class
于 2013-05-20T15:32:39.157 回答
0

总是在类名的开头使用大写字母。然后实例化你的类来调用它的实例方法。

class Lexicon(object):
    def scan(self, sentence):
        self.sentence = sentence
        self.words    = sentence.split()
        for word in self.words:
            if word in direction: # probably should be in and not is
                word = ('direction','%s' % word)

            return word

## in your test
def test_directions():
    lexicon_instance = Lexicon()
    assert_equal(lexicon_instance.scan("north"), [('direction', 'north')])
    result = lexicon_instance.scan("north south east")
    assert_equal(result, [('direction', 'north'),
                      ('direction', 'south'),
                      ('direction', 'east')])
于 2013-05-20T15:48:11.870 回答