python属性错误_检测Python中的TypeError和属性错误(LPTHW,练习48)

我正在努力学习Python的艰辛之路,练习48,使用nosetests来测试元组。我已经设置的鼻子测试如下:

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)如果我在“def scan(self):”上面引入了@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值