设为首页 加入收藏

TOP

Python装饰器与面向切面编程(三)
2017-09-30 17:54:19 】 浏览:10105
Tags:Python 装饰 面向 编程
sp;   end = time.clock()
         print  'used:' , end -  start
     return  wrapper
 
@timeit
def  foo():
     print  'in foo()'
 
foo()
print  foo.__name__

首先注意第5行,如果注释这一行,foo.__name__将是'wrapper'。另外相信你也注意到了,这个装饰器竟然带有一个参数。实际上,他还有另外两个可选的参数,assigned中的属性名将使用赋值的方式替换,而updated中的属性名将使用update的方式合并,你可以通过查看functools的源代码获得它们的默认值。对于这个装饰器,相当于wrapper = functools.wraps(func)(wrapper)。

2.3.2. total_ordering(cls): 
这个装饰器在特定的场合有一定用处,但是它是在Python 2.7后新增的。它的作用是为实现了至少__lt__、__le__、__gt__、__ge__其中一个的类加上其他的比较方法,这是一个类装饰器。如果觉得不好理解,不妨仔细看看这个装饰器的源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
53   def  total_ordering( cls ):
54       """Class decorator that fills in missing ordering methods"""
55       convert =  {
56           '__lt__' : [( '__gt__' , lambda  self , other: other < self ),
57                      ( '__le__' , lambda  self , other: not  other < self ),
58                      ( '__ge__' , lambda  self , other: not  self  < other)],
59           '__le__' : [( '__ge__' , lambda  self , other: other < =  self ),
60                      ( '__lt__' , lambda  self , other: not  other < =  self ),
61                      ( '__gt__' , lambda  self , other: not  self  < =  other)],
62           '__gt__' : [( '__lt__' , lambda  self , other: other > self ),
63                      ( '__ge__' , lambda  self , other: not  other > self ),
64                      ( '__le__' , lambda  self , other: not  self  > other)],
65           '__ge__' : [( '__le__' , lambda  self , other: other > =  self ),
66                      ( '__gt__' , lambda  self , other: not  other >
首页 上一页 1 2 3 4 下一页 尾页 3/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇冒泡,递归 下一篇爬虫——多线程糗事百科案例

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目