装饰器:
定义:本质是函数,主要目的是为了给其他的函数增加附加功能
原则:
1.不能修改被装饰函数的源代码
2.不能修改被装饰的函数调用方式
实现装饰器知识:
1.函数就是“变量”
2.高阶函数
a:把一个函数名当做实参传递给另外一个函数
b:返回值中包含函数名
eg:

def bar():
print 'in the bar'
def foo(func):
res=func()
return res
foo(bar)

优秀之处:

def foo(func):
return func
print 'Function body is %s' %(foo(bar))
print 'Function name is %s' %(foo(bar).func_name)
foo(bar)()
#foo(bar)() 等同于bar=foo(bar)然后bar()
bar=foo(bar)
bar()

3.嵌套函数
eg:

def foo():
print 'in the foo'
def bar():
print 'in the bar'
bar()
foo()
# bar()

局部与全局作用域的访问顺序:由内层向外层逐层查找

x=0
def grandpa():
# x=1
def dad():
x=2
def son():
x=3
print x
son()
dad()
grandpa()

高阶函数+嵌套函数==>>装饰器
eg:

import  time
def timer(func):#timer(test1)  func=test1
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)#run test1()
stop_time=time.time()
print("the func run time is %s" %(stop_time-start_time))
return deco
@timer #test1=timer(test1)
def test1():
time.sleep(3)
print("in the test1")
test1()
正文到此结束

本文标题:Python函数和常用模块-装饰器概念及示例

本文链接:https://www.hantaosec.com/314.html

除非另有说明,本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

声明:转载请注明文章来源及链接,不带链接禁止任何转载!访问任何网络安全相关文章,则视为默认接受网络安全文章免责声明 ,请认真阅读。

喜欢我的文章吗?
别忘了点赞或赞赏,让我知道创作的路上有你陪伴。