我正在努力学习使用nosetests测试元组的Python 48。我已经设置了nosetest如下:Python中的Nosetests TypeError和属性错误(LPTHW,练习48)
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)
如果我介绍@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
完美,谢谢! – 2012-07-13 03:21:43