Python class attribute delay calculation, python attribute Delay
The so-called latency Calculation of class attributes defines the class attributes as a property, which is calculated only when accessed. Once accessed, the results will be cached, you do not need to calculate it every time.
Advantages
The main purpose of constructing a delayed computing attribute 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 valueimport mathclass 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
Description
Defines a LazyProperty class for delayed computing. Circle is used for testing. The Circle class has three attributes: radius, area, and perimeter ). LazyProperty is decorated with the property of area and perimeter. Let's try the magic of LazyProperty:
>>> c = Circle(2)>>> print c.areaComputing area12.5663706144>>> print c.area12.5663706144
"Computing area" is printed every time calculated in area (). After Calling c. area twice in a row, "Computing area" is printed only once. This benefits from LazyProperty. After a call, no matter how many subsequent calls are called, the calculation will not be repeated.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.