from functools import cached_property
class Foo():
@cached_property
def myfunc(self):
print('using myfunc')
return 20
def func1(self):
return 1
if __name__ == '__main__':
F = Foo()
print(F.myfunc)
print('*'*30)
print(F.myfunc)
print(F.func1())
最终输出的结果为:
using myfunc
20
******************************
20
1
使用cached_property修饰过的函数,变成了对象的属性,当第一次引用该属性时,会调用该函数,以后再调用该属性时,会直接从字典中取了。
这里 myfunc 是一个属性,而func1是一个方法。
源代码
class cached_property(object):
"""
Decorator that converts a method with a single self argument into a
property cached on the instance.
Optional ``name`` argument allows you to make cached properties of other
methods. (e.g. url = cached_property(get_absolute_url, name='url') )
"""
def __init__(self, func, name=None):
self.func = func
self.__doc__ = getattr(func, '__doc__')
self.name = name or func.__name__
def __get__(self, instance, cls=None):
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
return res
本文介绍了Python3.8引入的新特性`@cached_property`装饰器,它能够将函数转换为对象的缓存属性。首次调用时计算值并存储,后续调用直接从缓存中获取,提高效率。示例中对比了`myfunc`属性与`func1`方法的区别。

2万+

被折叠的 条评论
为什么被折叠?



