编程语言
首页 > 编程语言> > ex48艰难学习Python

ex48艰难学习Python

作者:互联网

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是我正在做的工作,我不知道为什么我的程序没有通过测试.当我运行nosetests时,我得到了这个错误.

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)

我只把测试的第一个aprt放在我的测试目录中.就是这个:

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')])

解决方法:

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

标签:python,nosetests
来源: https://codeday.me/bug/20190831/1779211.html