为什么我在此 Python 代码上收到断言错误?
Why am I getting an Assertion Error on this Python code?
我在这里写了一个函数:
def addItem(aBookcase, name, mediaType):
"""
Returns False if aBookcase is full, otherwise returns True and
adds item of given name and mediaType to aBookcase.
"""
pass
emptySpacesBefore = aBookcase.getEmptySpaces()
if aBookcase.getEmptySpaces() == 0:
added = False
return added
else:
position = findSpace(aBookcase)
aBookcase.setName(*position, name=name)
aBookcase.setType(*position, mediaType=mediaType)
added = True
emptySpacesAfter = aBookcase.getEmptySpaces()
assert added is True, "No free positions"
assert emptySpacesAfter < emptySpacesBefore, "Same amount of empty spaces"
assert aBookcase.getName(*position) is name, "Error with name"
assert aBookcase.getType(*position) is mediaType, "Error with media type"
然而当我用这行代码去测试功能时:
assert addItem(small, "Algorhythms, date structures and compatibility", BOOK)
我得到一个 'AssertionError',如下所示:
所以如果我是对的,那就意味着我没有处理它,但我不确定如何处理或为什么处理?我的代码有问题吗?少了什么?等等
当它正常工作时,你的 addItem
函数 return 什么都没有,所以它 return 是 None
,这被最后一个 assert
您插入的语句。对于这两种情况(True
或 False
),您应该 return added
顺便说一句,既然你到达了那条线,这意味着之前所有的断言都是正确的好消息:你的代码是正确的。
我在这里写了一个函数:
def addItem(aBookcase, name, mediaType):
"""
Returns False if aBookcase is full, otherwise returns True and
adds item of given name and mediaType to aBookcase.
"""
pass
emptySpacesBefore = aBookcase.getEmptySpaces()
if aBookcase.getEmptySpaces() == 0:
added = False
return added
else:
position = findSpace(aBookcase)
aBookcase.setName(*position, name=name)
aBookcase.setType(*position, mediaType=mediaType)
added = True
emptySpacesAfter = aBookcase.getEmptySpaces()
assert added is True, "No free positions"
assert emptySpacesAfter < emptySpacesBefore, "Same amount of empty spaces"
assert aBookcase.getName(*position) is name, "Error with name"
assert aBookcase.getType(*position) is mediaType, "Error with media type"
然而当我用这行代码去测试功能时:
assert addItem(small, "Algorhythms, date structures and compatibility", BOOK)
我得到一个 'AssertionError',如下所示:
所以如果我是对的,那就意味着我没有处理它,但我不确定如何处理或为什么处理?我的代码有问题吗?少了什么?等等
当它正常工作时,你的 addItem
函数 return 什么都没有,所以它 return 是 None
,这被最后一个 assert
您插入的语句。对于这两种情况(True
或 False
),您应该 return added
顺便说一句,既然你到达了那条线,这意味着之前所有的断言都是正确的好消息:你的代码是正确的。