码迷,mamicode.com
首页 > 编程语言 > 详细

Python 装饰器

时间:2016-08-14 10:12:06      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

1.装饰器

1.函数调用顺序:其他高级语言类似,python不允许在函数未声明之前,对其进行引用或者调用

错误示范:

技术分享
 1 def foo():
 2     print(in the foo)
 3     bar()
 4 foo()
 5 
 6 报错:
 7 in the foo
 8 Traceback (most recent call last):
 9   File "<pyshell#13>", line 1, in <module>
10     foo()
11   File "<pyshell#12>", line 3, in foo
12     bar()
13 NameError: global name bar is not defined
14 
15 def foo():
16     print(foo)
17     bar()
18 foo()
19 def bar()
20     print(bar)
21 报错:NameError: global name bar is not defined
View Code

正确示范:(注意,python为解释执行,函数foo在调用前已经声明了bar和foo,所以bar和foo无顺序之分)

技术分享
def foo()
    print(in the foo)
    bar()
def bar():
    print(in the bar)
foo()

def bar():
    print(in the bar)
def foo():
    print(in the foo)
    bar()
foo()
View Code

2.高阶函数

满足下列条件之一就可成函数为高阶函数

  1.某一函数当做参数传入另一个函数中

  2.函数的返回值包含n个函数,n>0

高阶函数示范:

技术分享
def bar():
    print(in the bar)
def foo(func):
    res=func()
    return res
foo(bar)
View Code

 

Python 装饰器

标签:

原文地址:http://www.cnblogs.com/smile1/p/5769488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!