标签:roc UNC python学习 time test war 基本 div tar
函数闭包举例:
def father(name): print(‘hello world‘) def son(): print(‘儿子说:我的爸爸是%s‘ % name) def grandfson(): print(‘孙子说:我的爷爷是%s‘ % name) grandfson() son() father(‘小明‘)
运行结果:
hello world
儿子说:我的爸爸是小明
孙子说:我的爷爷是小明
Process finished with exit code 0
函数的包: 就是嵌套里的一层一层的函数
闭: 就是封装的意思
import time # 装饰器框架 def timmer(func): def wrapper(): start_time = time.time() func() stop_time = time.time() print(‘运行时间为;%s‘ %(stop_time-start_time)) return wrapper @timmer def test(): time.sleep(1) print(‘test函数运行完毕‘) # test =timmer(test) 相当于 @timmer test()
运行结果;
test函数运行完毕 运行时间为;1.000901460647583 Process finished with exit code 0
import time # 装饰器框架 def timmer(func): def wrapper(): start_time = time.time() res = func() # 就是在运行test() stop_time = time.time() print(‘运行时间为;%s‘ %(stop_time-start_time)) return res return wrapper @timmer # test = timmer(test) def test(): time.sleep(1) print(‘test函数运行完毕‘) return ‘132‘ res =test() # print(res)
运行结果:
test函数运行完毕 运行时间为;1.000777244567871 132 Process finished with exit code 0
------函数闭包加上参数
import time
# 装饰器框架
def timmer(func):
def wrapper(*args,**kwargs): # *args 元组的形式,最多可传3个值。 **kwargs 字典,相当于:wrapper(*(name,age,gender),**{ })
start_time = time.time()
res = func(*args,**kwargs)
stop_time = time.time()
print(‘运行时间为;%s‘ %(stop_time-start_time))
return res
return wrapper
@timmer # test = timmer(test)
def test(name,age):
time.sleep(1)
print(‘test函数运行完毕,名字:%s 年龄: %s‘ % (name,age))
return ‘132‘
ret = test(‘小王‘,20)
print(ret)
@timmer
def test1(name,age,gender):
time.sleep(1)
print(‘test1名字:%s,年龄%s,性别:%s‘ %(name,age,gender))
return ‘321‘
res =test1(‘小红‘,18,‘男‘)
print(res)
运行结果:
test函数运行完毕,名字:小王 年龄: 20 运行时间为;1.0007729530334473 132 test1名字:小红,年龄18,性别:男 运行时间为;1.0006530284881592 321 Process finished with exit code 0
标签:roc UNC python学习 time test war 基本 div tar
原文地址:https://www.cnblogs.com/liujinjing521/p/11213373.html