您的位置:首页 > 编程语言 > Python开发

Python 装饰器

2017-09-16 23:37 330 查看
#装饰器目的:是在执行原函数之前或之后做点其他的事

#装饰器(前)
def outer(func):
def inner():
print("hello")
print("hello")
print("hello")
return func()
return inner

@outer
def f1():
print("F1")

f1()




#装饰器(后)
def outer(func):
def inner():
print("hello")
print("hello")
print("hello")
r= func()
print('CCC')
print('CCC')
print('CCC')
return r
return inner

@outer
def f1():
print("F1")

f1()




#1、执行outer函数,并且将其下面的函数名当做参数

#2、将outer的返回值重新赋值给f1=outer的返回值

#新f1函数 = inner

上面是没有参数的,来两个有参数的

#装饰器(后)
def outer(func):
def inner(a1,a2):
print("hello")
print("hello")
print("hello")
r= func(a1,a2)
print('CCC')
print('CCC')
print('CCC')
return r
return inner

@outer
def f1(a1,a2):
print("F1")
return a1+a2
print(f1(1,2))


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: