任何在全球范围内的功能之外将作为脚本的一部分来执行:
def closest_to(l,v):
num = l[0]
diff_min = abs(l[0] - v)
for i in xrange(1,len(l)):
diff = abs(l[i] - v)
if diff < diff_min:
diff_min = diff
num = l[i]
return num
result = closest_to(val1, val2)
print result
如果你想有test.py仅与函数的定义,并想从调用这些功能另一个文件,可以从需要使用任何函数的文件中导入test.py。
# Some-other-file.py
import test
result = test.closest_to(val1, val2)
print result
如果test.py包含了很多功能,你知道你将只使用其中的几个,你可以导入这些特定的少数。
# Another-file.py
from test import closest_to, farthest_to
result = closest_to(val1, val2)
print result
farthest_to(val1, val2)
我做了一个假设,即功能farthest_to没有任何返回值,所以没有尝试存储或打印。如果你试图存储/打印这样的值,你会得到无。
http://stackoverflow.com/questions/3371255/writing-unit-tests-in-python- how-do-i-start – 2013-02-27 03:31:40