#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-01-23 15:05
# @Author :
# @File : lazyproperty.py
# @Software: Pycharm professional
import math
class lazyroperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
class Circle:
def __init__(self, radius):
self.radius = radius
@lazyroperty
def area(self):
print("computing area")
return math.pi * self.radius ** 2
if __name__ == '__main__':
c = Circle(4.0)
print(c.area)
print(c.area)
可以看到上面代码的输出只有一遍"computing area",惰性属性的全部意义就是用于提升程序性能,一旦访问了该属性就不会每次访问它的时候重新计算。
Python的hasattr() getattr() setattr() 函数使用方法详解:https://www.cnblogs.com/cenyu/p/5713686.html