Home > Backend Development > Python Tutorial > Lazy evaluation of Python class attributes

Lazy evaluation of Python class attributes

高洛峰
Release: 2016-11-22 14:29:16
Original
1301 people have browsed it

The so-called delayed calculation of class attributes is to define the attributes of the class as a property, which will only be calculated when accessed, and once accessed, the result will be cached and does not need to be calculated every time.

Advantages

The main purpose of constructing a lazy calculation 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 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
Copy after login

Description

defines a lazy calculation decorator class LazyProperty. Circle is a class used for testing. The Circle class has three attributes: radius, area, and perimeter. The properties of area and perimeter are decorated by LazyProperty. Let's try the magic of LazyProperty:

>>> c = Circle(2)
>>> print c.area
Computing area
12.5663706144
>>> print c.area
12.5663706144
Copy after login

"Computing area" will be printed every time it is calculated in area(), and after calling c.area twice in a row, "Computing area" will be printed. " was printed only once. This is due to LazyProperty, as long as it is called once, it will not be counted again no matter how many subsequent calls are made.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template