if __name__ == '__main__': # 此语句输出<module 'tests.test2' from '/Users/apple/PycharmProjects/test-framework/tests/test2.py'> print(inspect.getmodule(hello))
执行结果:
inspect.getfile
inspect.getfile(object) 用来返回 object 定义在哪个 file 中。
test1.py添加执行代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import inspect
from tests.test2 import hello
classMayTest(object): def__init__(self): print("My name is May")
defsum(*kwargs): total = 0 for ele in kwargs: total = total + ele return total
现在,我们加了需求,需要记录这个函数开始的时间和结束的时间。 正常情况下,我们的代码是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import time
defsum(*kwargs): print('function start at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) total = 0 for ele in kwargs: total = total + ele print('function end at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) return total
defsum(*kwargs): total = 0 for ele in kwargs: total = total + ele return total
defrecord_time(*kwargs): print('function start at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) total = sum(*kwargs) print('function end at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) return total
if __name__ == '__main__': print(record_time(1, 2, 3, 4))
以后我们再给函数加有关时间处理的功能,加到 record_time 里好了,而 sum 函数根本不用变。那这个函数还能更加简化吗?
defsum(*kwargs): total = 0 for ele in kwargs: total = total + ele return total
defrecord_time(func): defwrapper(*kwargs): print('function start at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) total = func(*kwargs) print('function end at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) return total
return wrapper
if __name__ == '__main__': print(record_time(sum)(1, 2, 3, 4))
执行结果:
假设我们的需求又变化啦,我们现在不统计函数的运行开始和结束时间了,改成统计函数的运行时长了,那么我们只需要改 record_time 这个函数就好了,而我们的功能函数 sum 就无须再改了,这样是不是方便了很多?
defrecord_time(func): defwrapper(*kwargs): print('function start at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) total = func(*kwargs) print('function end at {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) return total
return wrapper
@record_time defsum(*kwargs): total = 0 for ele in kwargs: total = total + ele return total