SoFunction
Updated on 2024-11-19

Deferred Computation of Python Class Attributes

The so-called deferred computation of class properties is to define a class property as a property that will be computed only when accessed, and once accessed, the result will be cached without having to be computed every time.

vantage

The main purpose of constructing a deferred computation attribute is to improve performance

realization

class LazyProperty(object):
  def __init__(self, func):
     = func

  def __get__(self, instance, owner):
    if instance is None:
      return self
    else:
      value = (instance)
      setattr(instance, .__name__, value)
      return value


import math


class Circle(object):
  def __init__(self, radius):
     = radius

  @LazyProperty
  def area(self):
    print 'Computing area'
    return  *  ** 2

  @LazyProperty
  def perimeter(self):
    print 'Computing perimeter'
    return 2 *  * 

clarification

LazyProperty defines a decorator class for delayed computation. Circle is the class used for testing, the Circle class has is three properties radius, area and perimeter. The area and perimeter properties are decorated by LazyProperty. Here's how to try the magic of LazyProperty:

>>> c = Circle(2)
>>> print 
Computing area
12.5663706144
>>> print 
12.5663706144

In area(), "Computing area" is printed once for each calculation, while "Computing area" is printed only once after two consecutive calls. Thanks to LazyProperty, once it is called once, it will not be repeated no matter how many times it is called.

This is the entire content of this article.