Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools cached_property() Function



The Pythoncached_property() function transforms a method of a class into a property, where its value is computed only once and this value will be cached as a normal attribute. Here, the result is stored when the method is executed for the first time.

This function improves the performance of a program by avoiding the duplicate calculations and simplifies code by allowing method.

Syntax

Following is the syntax for the function.

@cached_property()

Parameters

This function doesn't accept any parameters.

Return Value

Decorator returns the cached result from the decorated method.

Example 1

In this example, we are calculating the area of a circle using thecached_property() decorator. The result is cached, so subsequent accesses to the area returns the cached value without recalculating.

from functools import cached_propertyclass Circle:    def __init__(self, rad):        self.rad = rad    @cached_property    def area(self):        print("Calculating area of a circle.")        return 3.14159 * self.rad ** 2circle = Circle(23)print(circle.area) print(circle.area)

Output

The result is generated as follows −

Calculating area of a circle.1661.901111661.90111

Example 2

Now, we compute the total_sum of the numbers using thecached_property function. This result will be stored, so future accesses to total_sum retrieves the cached value without recalculating.

from functools import cached_propertyclass NumSeries:    def __init__(self, num):        self.num = num    @cached_property    def total_sum(self):        print("Sum of the numbers")        return sum(self.num)series = NumSeries([21, 3, 12, 45, 65])print(series.total_sum)  print(series.total_sum)

Output

The code is generated as follows −

Sum of the numbers146146

Example 3

In the below code, thecached_property() decorator is used to cache the result of the function, converting the lowercase letters to uppercase.

from functools import cached_propertyclass MyString:    def __init__(self, text):        self.text = text    @cached_property    def upper_text(self):        return self.text.upper()s = MyString("welcome to tutorialspoint")print(s.upper_text) print(s.upper_text)

Output

The output is obtained as follows −

WELCOME TO TUTORIALSPOINTWELCOME TO TUTORIALSPOINT
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp