我不明白为什么会收到此错误,因为当我将“height”传递为-1时,必须将“error”更改为“Height must be .GE to zero”
测试用例通过了。
但是,当我测试基本案例0时,它说列表中没有内容?有人可以解释为什么吗?或告诉我我的代码有什么问题
def adjust(values):
#default
height = 0
if ('height' in values):
try:
height = float(values['height'])
except ValueError:
values['error'] = 'non-numeric height'
return values
if height < 0:
values['error'] = 'Heights needs to be .GE 0'
return values
测试案例:100_101失败并且100_120通过
def test100_010HeightLowBound(self):
dict = nav.adjust({'op': 'adjust', 'observation': '3d.13','height': '0'})
self.assertEquals('0', dict['height'])
def test100_020OutofBound(self):
dict = nav.adjust({'op': 'adjust', 'observation': '3d1.3', 'height': '-1'})
self.assertEquals('Heights needs to be .GE 0', dict['error'])
由于测试失败而产生错误:
self.assertEquals('0',dict ['height'])
TypeError:“NoneType”对象没有属性“ getitem ”
最佳答案
如果存在height
键和height >= 0
,则不会返回任何内容。这意味着dict
将是None
,并且您会得到错误。您只需要确保在所有实例中都返回一个可用的值。
def adjust(values):
height = 0
if ('height' in values):
try:
height = float(values['height'])
except ValueError:
values['error'] = 'non-numeric height'
return values
if height < 0:
values['error'] = 'Heights needs to be .GE 0'
return values # Return values regardless of the previous checks
似乎甚至没有必要返回
values
。您要做的就是更改参数。您可以只使用mutated参数。def adjust2(values):
height = 0
if ('height' in values):
try:
height = float(values['height'])
except ValueError:
values['error'] = 'non-numeric height'
return
if height < 0:
values['error'] = 'Heights needs to be .GE 0'
def test100_010HeightLowBound(self):
data = {'op': 'adjust', 'observation': '3d.13','height': '0'}
nav.adjust(data)
self.assertEquals('0', data['height'])
并且如注释中所述,给变量命名与内置变量相同的名称是一个坏主意。我将
dict
重命名为data
,因此您不会隐藏内置的dict
函数。
关于python - PYTHON : TypeError: 'NoneType' object has no attribute '__getitem__' for TESTCASE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815514/