Search code examples
pythonnosetests

ex48 Learn Python the hard way


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 is what I am working on, I don't know why my program doesn't pass the test. When I run nosetests I get this error.

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)

and I only put the first aprt of the test in my tests directory. It is this:

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

Solution

  • lexicon.scan
    

    is an instance method, not a class or static method. You have to construct a lexicon, then call scan on that.

    lex = lexicon() # This will create an instance of the lexicon class
    lex.scan() # This will invoke the instance method of the instantiated class