2

我是一个通过Learn Python the Hard Way 工作的新手。

这个练习的重点是编写一个字扫描仪,当它由提供的单元测试运行时,它通过了鼻子测试。

在以下提供的单元测试上运行鼻子测试时,我收到了这个错误:

`TypeError:必须使用词典实例作为第一个参数调用未绑定的方法scan()(改为获取str实例)

课程提供的测试

from nose.tools import *
from ex48 import lexicon

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

经过一番调查,我在这里发现了一个正在做同样练习的用户:

鼻子测试,蟒蛇

python变量,类

那里的答案建议在单元测试中实例化(实例化?)该方法。所以我做了以下修改,并在文件 ex48.py 中编写了我的类,它通过了鼻子测试。

修改后的测试

from nose.tools import *
from ex48 import lexicon


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

ex48.py - 扫描仪

class lexicon(object):

    def __init__(self, data):
        #nosetests fails me if I don't put in some dummy
        # __init__ function with a dummy line, not sure why.
    self.direction = data

    def scan(self, data):
        split_data = data.split()
        directions = ['north', 'south', 'east', 'west']
        data_reply = []
        #for loop for the length of the list
        for split_data_item in split_data:
            #If data is in the directions list
            if split_data_item in directions:
                #Add [('direction', data)] to a dict
                data_reply.append(('direction', split_data_item))

        #Return the list
        return data_reply

我不确定是否要更改单元测试。我在这里找到了关于“直接实例化对象”的线索:

Python:“直接”调用方法会实例化对象吗?

但不确定这是否适用。可以使扫描仪实例化自身,还是提供的单元测试是一个技巧“问题”并且必须修改?

4

2 回答 2

4

Learn Python The Hard Way的在线版本中,他们有:

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.py 文件来测试。

它拼写为实例化(就像我正在制作这个类的一个实例一样)。

于 2011-07-30T21:48:12.370 回答
2

您应该保持测试原样,并@staticmethod在扫描方法上使用装饰器。这样,您将能够直接从类中调用该方法,而无需为此实例化对象。

class lexicon(object):

   @staticmethod
   def scan(data):
      #do the stuff here
于 2011-07-30T21:31:50.313 回答