我有使用dockets的简单Python代码
#!/usr/bin/python
# http://stackoverflow.com/questions/2708178/python-using-doctests-for-classes
class Test:
def __init__(self, number):
self._number=number
def multiply_by_2(self):
"""
>>> t.multiply_by_2()
4
"""
return self._number*2
if __name__ == "__main__":
import doctest
doctest.testmod(extraglobs={'t': Test(2)})
我可以将它与python解释器一起使用:
> python simple.py
但是,当我从doctest模块执行代码时,我收到此错误:
> python -m doctest simple.py
**********************************************************************
File "simple.py", line 10, in simple.Test.multiply_by_2
Failed example:
t.multiply_by_2()
Exception raised:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1289, in __run
compileflags, 1) in test.globs
File "<doctest simple.Test.multiply_by_2[0]>", line 1, in <module>
t.multiply_by_2()
NameError: name 't' is not defined
**********************************************************************
1 items had failures:
1 of 1 in simple.Test.multiply_by_2
***Test Failed*** 1 failures.
为什么会有这种差异?如何解决这个问题?
答案 0 :(得分:3)
不同之处在于,当您通过sorted_df <- unsorted_df
for (i in 1:(nrow(sorted_df)-1)){
similarity <- which.max(sapply((i+1):nrow(sorted_df),function(x) sum(sorted_df[x,]*sorted_df[i,])))
temp <- sorted_df[i+1,]
sorted_df[i+1,] <- sorted_df[i+similarity,]
sorted_df[i+similarity,] <- temp
}
#> sorted_df
# c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12
#1 1 1 1 0 0 0 1 0 0 0 0 0
#2 0 1 1 1 0 0 0 0 0 0 0 0
#3 0 0 0 0 0 0 0 0 1 1 1 1
#4 0 0 0 0 0 1 1 0 0 0 0 0
#5 0 0 0 0 0 1 1 0 0 0 0 0
#6 0 0 0 0 0 1 0 0 0 0 0 0
#7 0 0 0 0 0 1 0 1 0 0 0 0
#8 0 0 0 0 0 1 0 0 0 0 0 0
#9 0 0 0 0 0 1 0 0 0 0 0 0
#10 0 0 0 0 0 0 0 0 0 0 0 0
执行时,doctest
模块与直接执行脚本的__main__
块将执行的位置进行比较。
除了将所需的所有信息都放在docstring本身之外,我不知道一个好的解决方案:
if __name__ == '__main__'
这将带来额外的好处,即阅读您的文档字符串的用户将知道发生了什么......他们不会偶然发现您的{{1} }关键字,以确定def multiply_by_2(self):
"""
>>> t = Test(2)
>>> t.multiply_by_2()
4
"""
return self._number * 2
是什么以及如何初始化。