python修饰器

来源:互联网 发布:php验证码源码 编辑:程序博客网 时间:2024/05/01 18:11

看了一下flask,发现不知python的修饰器是啥

直接上代码:

////代码1//////

#coding:utf-8import __main__def dec(param):    print(type(param))    print(str(param))        param("on dec")    return param@decdef foo(str):    print(str)    if(__name__ == '__main__'):    foo("some str")

输出:

<type 'function'>
<function foo at 0x7fcd54ce6c08>
on dec
some str


可以看出,修饰器把函数foo作为参数传给了被修饰的函数dec。

注意,如果吧

if(__name__ == '__main__'):    foo("some str")
这句去掉,则输出为:

<type 'function'>
<function foo at 0x7f38428b9c08>
on dec

可见修饰器不管函数有没执行,都会把foo函数传给dec,并执行dec函数


最后再看一段代码:

///代码2///////

#coding:utf-8import __main__def bar(str):    print("on bar")    print (str)        def otherFunc(param):        print("on otherFunc")        print(param)        return param        return otherFunc    @bar("some")def foo(str):    print("on foo")    print(str)if(__name__ == '__main__'):    foo("hihi") 

输出结果:

on bar
some
on otherFunc
<function foo at 0x7f3b821c7c80>
on foo
hihi


执行过程为:

1。运行bar("some"),返回函数otherFunc,

2。对otherFunc进行修饰,函数foo作为参数传入otherFunc,返回foo

3。执行foo


有时候觉得python某些特性真的很奇怪


0 0
原创粉丝点击