def test_fib(): fun = fib.fib2(1000) lst2 = [] while True: n = fun() if n != None: lst2.append(n) else: break assert lst2 == list(fib.fib(1000))
def test_fib2(): try: assert None == fib.fib2(-1) except fib.InvalidInputError: pass assert fib.fib1(0) == fib.fib2(0) assert fib.fib1(1) == fib.fib2(1) assert fib.fib1(2) == fib.fib2(2) assert fib.fib1(3) == fib.fib2(3) assert fib.fib1(4) == fib.fib2(4) assert fib.fib1(5) == fib.fib2(5) assert fib.fib1(6) == fib.fib2(6)
def test_fib3(self): with self.assertRaises(fib.InvalidInputError): fib.fib3(-100) with self.assertRaises(fib.InvalidInputError): fib.fib3(-1) self.assertEqual(fib.fib3(0), fib.fib2(0)) self.assertEqual(fib.fib3(1), fib.fib2(1)) self.assertEqual(fib.fib3(2), fib.fib2(2)) self.assertEqual(fib.fib3(3), fib.fib2(3)) self.assertEqual(fib.fib3(4), fib.fib2(4)) self.assertEqual(fib.fib3(5), fib.fib2(5)) self.assertEqual(fib.fib3(6), fib.fib2(6))
#to show the basics of linking multiple modules together import factorial #allows access to all functions, etc... in file factorial.py from fib import fib2 #allows access to a specific function (fib) in file fib.py without referencing fib.py as a whole (IE: fib(x) instead of fib.fib(x)) from factorial import * #allows importing of all functions in factorial that don't start with a '_' (IE: factorial._fac will not be available) import moreStuff.subdirectoryFib #notice that accessing modules in subdirectories uses a '.' instead of a '/' for navagating through directories import factorial as temp #allows importing of modulea and functions, but changing the name it is refered to in your program (IE: this allows accessing everthing in the 'factorial' module using the name 'temp') print("8! = " + str(factorial.factorial_1(8))) print("fib(8)= " + str(fib2(8))) print("8! = " + str(factorial_1(8))) print("fib(8)= " + str(moreStuff.subdirectoryFib.fib(8))) print("8! = " + str(temp.factorial_1(8)))
# fib.py must be in the same directory # import pkg.fib import fib fib.fib(100) print "fib2 demo" print fib.fib2(100)
def find_sum_longer_than(mylen): for i,n in enumerate(fib.fib2(),1): #print i,n if len(str(n)) > mylen: return i
# File: main.py # Demonstration of module import import fib fib.fib(10) # Outputs: 1 1 2 3 5 8 print(fib.fib2(2)) # Outputs: [1, 1]
# 这样可以导入所有除了下划线(_)开头的命名 from sys import * # 引入斐波那契数列方法文件 import fib # 还可以写成,这样可以直接使用fib2调用方法 from fib import fib2 # 调用函数 print(fib.fib2(10)) print(fib.__name__) # 可以给方法赋值一个本地变量,这个变量相当于xxx.func current_func_name = fib.fib2 print(current_func_name(20))
import fib # f = fib.fibo # f(100) fib.fibo(1000) for fibo, fib2 import fib fib.fib2(500) from fib import * fib(500) import fib as fi fi.fib(500) from fibo import fib as fib