import time
#计算一个函数的运行时间的装饰器
def timer(func):
def wrapper(*kargs,**kwargs):
start_time=time.time()
func()
end_time=time.time()
print("the func runtime is %s"%(end_time-start_time))
return wrapper
@timer
def test1():
time.sleep(3)
print("in the test1....")
test1()
#高阶函数
def bar():
print("in the bar...")
def test(func):
print(func)#打印出该函数变量的地址
func()
test(bar)
# 把一个函数名当做实参传递给另一个函数
import time
def bar():
time.sleep(2)
print("in the bar...")
def test(func):
start_time=time.time()
func() #run bar()
end_time=time.time()
print(" the func runtime is %s"%(end_time-start_time))
test(bar)
# 返回值中包含函数名
import time
def bar():
time.sleep(2)
print("in the bar...")
def test2(func):
print(func)
return func
bar2=test2(bar)
bar2()
#嵌套函数
#局部作用域和全局作用域的访问顺序
x=0
def grandpa():
x=1
print("grandpa:",x)
def dad():
x=2
print("dad:",x)
def son():
x=3
print("son:",x)
son()
dad()
grandpa()
#匿名函数:没有定义函数名字的函数
calc=lambda x,y:x+y
print(calc(13,15))
import time
def timer(func):
def deco(*kargs,**kwargs):
start_time=time.time()
func(*kargs,**kwargs)
end_time=time.time()
print(" the func runtime is %s"%(end_time-start_time))
return deco
@timer # test1=timer(test1)
def test1():
time.sleep(2)
print("in the test1.....")
# test1=timer(test1)
test1()
@timer
def test2(name,age):
time.sleep(3)
print("in the test2:",name,age)
test2("Jean_V",20)