python中的装饰器

关于装饰器先看这一篇文章:

http://www.cnblogs.com/tingfenglin/p/5592385.html

 

写得比较全面的是这一篇:

http://blog.csdn.net/dreamcoding/article/details/8611578

 

 

 1 def lazyproperty(func):   #func: area
 2     name = '_lazy_' + func.__name__
 3     @property
 4     def lazy(self):
 5         if hasattr(self, name):
 6             return getattr(self, name)
 7         else:
 8             value = func(self)
 9             setattr(self, name, value)
10             return value
11     return lazy
12 
13 import math
14 
15 class Circle:
16     def __init__(self, radius):
17         self.radius = radius
18 
19     @lazyproperty
20     def area(self):
21         print('Computing area')
22         return math.pi * self.radius ** 2
23 
24     @lazyproperty
25     def perimeter(self):
26         print('Computing perimeter')
27         return 2 * math.pi * self.radius
28 
29 c=Circle(4.0)
30 c.area

 程序中如果没有@property,第30行就要变成c.area()

posted on 2017-02-05 23:36  wzxds02  阅读(146)  评论(0编辑  收藏  举报

导航