Lazy calculation of Python class attributes
- 2020-05-17 05:41:25
- OfStack
The so-called deferred calculation of class attributes is to define the class attributes as 1 property, which will only be calculated when accessed, and once 1 is accessed, the results will be cached, instead of being calculated every time.
advantages
The main purpose of constructing a deferred computation property is to improve performance
implementation
class LazyProperty(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
import math
class Circle(object):
def __init__(self, radius):
self.radius = radius
@LazyProperty
def area(self):
print 'Computing area'
return math.pi * self.radius ** 2
@LazyProperty
def perimeter(self):
print 'Computing perimeter'
return 2 * math.pi * self.radius
instructions
Defines a delay calculation decorator class LazyProperty. Circle is the class used for testing. Circle has three attributes: radius (radius), area (area) and circumference (perimeter). The area and perimeter properties are decorated by LazyProperty. Try LazyProperty's magic below:
>>> c = Circle(2)
>>> print c.area
Computing area
12.5663706144
>>> print c.area
12.5663706144
In area(), "Computing area" is printed once for every calculation, and "Computing area" is printed only once after two consecutive calls to c.area. This is thanks to LazyProperty, which does not double count as long as it is called once, no matter how many subsequent calls are made.