我有一个像这样的示例文档测试。
"""
This is the "iniFileGenerator" module.
>>> hintFile = "./tests/unit_test_files/hint.txt"
>>> f = iniFileGenerator(hintFile)
>>> print f.hintFilePath
./tests/unit_test_files/hint.txt
"""
class iniFileGenerator:
def __init__(self, hintFilePath):
self.hintFilePath = hintFilePath
def hello(self):
"""
>>> f.hello()
hello
"""
print "hello"
if __name__ == "__main__":
import doctest
doctest.testmod()
当我执行这段代码时,我得到了这个错误。
Failed example:
f.hello()
Exception raised:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1254, in __run
compileflags, 1) in test.globs
File "<doctest __main__.iniFileGenerator.hello[0]>", line 1, in <module>
f.hello()
NameError: name 'f' is not defined
此错误是由访问测试hello()
方法时无法访问的“f”引起的。
有什么方法可以共享之前创建的对象吗?没有它,就需要在必要时始终创建对象。
def hello(self):
"""
hintFile = "./tests/unit_test_files/hint.txt"
>>> f = iniFileGenerator(hintFile)
>>> f.hello()
hello
"""
print "hello"