一、内部函数
def outer():
def inner():
x = 10
二、闭包
n = 'hello'
def outer(arg):
def inner():
arg
return inner
f = outer(n)
三、装饰器:
原始方式
def n():
print("hello world")
def outter(arg):
def inner():
print("*" * 20)
arg()
return inner
n = outer(n)
n()
语法糖
def outter(arg):
def inner():
print("*" * 20)
arg()
return inner
def n():
print("hello world")
@outer
n()
四、装饰器固定格式
def auth(func):
def wrapper(*args,**kwargs):
# 写需要增加的代码
r = func(*args,**kwargs)
return r
return wrapper
@auth
def foo(msg):
up_msg = msg.upper()
return up_msg
r = foo('hello')
print(r)
五、带参的装饰器
def outer(falg):
def wrapper(func):
def inner(*args, **kwargs):
if flag:
print('before')
result = func(*args,**kwargs)
print('after')
else:
result = func(*args, **kwargs)
return result
return inner
return wrapper
六、多层装饰器
def do_something(arg):
def wrapper():
print('#' * 22)
arg()
print('#' * 22)
return wrapper
def decorator(func):
def wrapper():
print("*" * 19)
func()
print("*" * 19)
return wrapper
do_something(decorator)
@do_something # inner = do_something(decorator(inner))
@decorator
def inner():
print(" hello world")
print(" 单车欲问边,蜀国过居延")
inner()
eg.计算一个程序运行所需时间
import time
def timeit(func):
def test():
start = time.clock()
func()
end = time.clock()
print("time used:", end - start)
return test
@timeit
def sum():
sum = 1+2
print(sum)
sum()