我尝试使用doctest来跟踪源代码:
def add_greeting(L=[]):
""" (list) -> NoneType
Append 'hello' to L and print L.
>>> greetings_list = ['hi', 'bonjour']
>>> add_greeting(greetings_list)
>>> greetings_list
['hi', 'bonjour', 'hello']
"""
L.append('hello')
print(L)
if __name__ == '__main__':
import doctest
print(doctest.testmod())
当我像'python my_file.py'一样启动此文件时,我得到以下内容:
python my_file.py
**********************************************************************
File "my_file.py", line 9, in __main__.add_greeting
Failed example:
add_greeting(greetings_list)
Expected nothing
Got:
['hi', 'bonjour', 'hello']
**********************************************************************
1 items had failures:
1 of 3 in __main__.add_greeting
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=3)
有人可以帮我解决这个错误吗? 为什么我在这种情况下得到'没有期待'? 如何解决?
答案 0 :(得分:0)
尝试
def add_greeting(L=[]):
""" (list) -> NoneType
Append 'hello' to L and print L.
>>> greetings_list = ['hi', 'bonjour']
>>> add_greeting(greetings_list)
['hi', 'bonjour', 'hello']
>>> greetings_list
['hi', 'bonjour', 'hello']
"""
L.append('hello')
print(L)
if __name__ == '__main__':
import doctest
print(doctest.testmod())
您收到错误是因为print(L)
末尾有add_greeting
,但文档字符串中的示例控制台输出不希望add_greeting
打印或返回任何内容。