任何在全球範圍內的功能之外將作爲腳本的一部分來執行:
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