python:属性字段是自动缓存的吗?

xmjla07d  于 2023-01-29  发布在  Python
关注(0)|答案(8)|浏览(105)

我的问题是下面两段代码被解释器运行时是否相同:

class A(object):
  def __init__(self):
     self.__x = None

  @property
  def x(self):
     if not self.__x:
        self.__x = ... #some complicated action
     return self.__x

还有更简单的

class A(object):
  @property
  def x(self):
      return ... #some complicated action

也就是说,解释器是否足够智能,能够缓存属性x
我的假设是x不会改变--找到它是 * 很难 * 的,但是一旦你找到了一次就没有理由再找到它了。

ijnw1ujt

ijnw1ujt1#

不,每次访问该属性时都将调用getter。

6bc51xsx

6bc51xsx2#

不,您需要添加一个memoize装饰器:

class memoized(object):
   """Decorator that caches a function's return value each time it is called.
   If called later with the same arguments, the cached value is returned, and
   not re-evaluated.
   """
   def __init__(self, func):
      self.func = func
      self.cache = {}
   def __call__(self, *args):
      try:
         return self.cache[args]
      except KeyError:
         value = self.func(*args)
         self.cache[args] = value
         return value
      except TypeError:
         # uncachable -- for instance, passing a list as an argument.
         # Better to not cache than to blow up entirely.
         return self.func(*args)
   def __repr__(self):
      """Return the function's docstring."""
      return self.func.__doc__
   def __get__(self, obj, objtype):
      """Support instance methods."""
      return functools.partial(self.__call__, obj)

@memoized
def fibonacci(n):
   "Return the nth fibonacci number."
   if n in (0, 1):
      return n
   return fibonacci(n-1) + fibonacci(n-2)

print fibonacci(12)
s3fp2yjn

s3fp2yjn3#

对于任何可能在2020年阅读这篇文章的人来说,从Python 3.8开始,functools模块作为标准库的一部分提供了这个功能。
https://docs.python.org/dev/library/functools.html#functools.cached_property
需要注意的是,定义自己的__dict__(或者根本不定义)或者使用__slots__的类可能无法按预期工作。

wmvff8tz

wmvff8tz4#

属性不会自动缓存它们的返回值。getter(和setter)用于在每次访问属性时调用。
然而,Denis Otkidach已经为此编写了一个很棒的缓存属性装饰器(发布在the Python Cookbook, 2nd edition中,最初也发布在ActiveStatePSF license下):

class cache(object):    
    '''Computes attribute value and caches it in the instance.
    Python Cookbook (Denis Otkidach) https://stackoverflow.com/users/168352/denis-otkidach
    This decorator allows you to create a property which can be computed once and
    accessed many times. Sort of like memoization.

    '''
    def __init__(self, method, name=None):
        # record the unbound-method and the name
        self.method = method
        self.name = name or method.__name__
        self.__doc__ = method.__doc__
    def __get__(self, inst, cls):
        # self: <__main__.cache object at 0xb781340c>
        # inst: <__main__.Foo object at 0xb781348c>
        # cls: <class '__main__.Foo'>       
        if inst is None:
            # instance attribute accessed on class, return self
            # You get here if you write `Foo.bar`
            return self
        # compute, cache and return the instance's attribute value
        result = self.method(inst)
        # setattr redefines the instance's attribute so this doesn't get called again
        setattr(inst, self.name, result)
        return result

下面是一个演示其用法的示例:

def demo_cache():
    class Foo(object):
        @cache
        def bar(self):
            print 'Calculating self.bar'  
            return 42
    foo=Foo()
    print(foo.bar)
    # Calculating self.bar
    # 42
    print(foo.bar)    
    # 42
    foo.bar=1
    print(foo.bar)
    # 1
    print(Foo.bar)
    # __get__ called with inst = None
    # <__main__.cache object at 0xb7709b4c>

    # Deleting `foo.bar` from `foo.__dict__` re-exposes the property defined in `Foo`.
    # Thus, calling `foo.bar` again recalculates the value again.
    del foo.bar
    print(foo.bar)
    # Calculating self.bar
    # 42

demo_cache()
4urapxun

4urapxun5#

Python 3.2提供了一个内置的装饰器,你可以用它来创建LRU缓存:
@functools.lru_cache(maxsize=128, typed=False)
或者,如果您使用的是Flask / Werkzeug,则有@cached_property装饰器。
对于Django,尝试from django.utils.functional import cached_property

mbzjlibv

mbzjlibv6#

因为我也有同样的问题,所以我不得不查了一下。
来自标准库的functools包也会得到一个cached_property装饰器,不幸的是,它只在Python 3.8中可用(截至本文发表时,它是Python 3.8a0),替代等待的方法是使用一个定制的装饰器,比如this one as mentioned by 0xc0de)或Django的装饰器,现在,然后再切换:

from django.utils.functional import cached_property
# from functools import cached_property # Only 3.8+ :(
rwqw0loc

rwqw0loc7#

@unutbu的回答中提到的Denis Otkidach的decorator发表在O 'Reilly的Python Cookbook中,不幸的是,O' Reilly没有为代码示例指定任何许可证--就像重用代码的非正式许可一样。
如果你需要一个带有自由许可证的缓存属性装饰器,你可以使用Ken Seehof@cached_property,它是在MIT license下显式发布的。

def cached_property(f):
    """returns a cached property that is calculated by function f"""
    def get(self):
        try:
            return self._property_cache[f]
        except AttributeError:
            self._property_cache = {}
            x = self._property_cache[f] = f(self)
            return x
        except KeyError:
            x = self._property_cache[f] = f(self)
            return x

    return property(get)
k2arahey

k2arahey8#

注:为了可用选项的完整性而添加。
不,property默认不缓存。但是有几个选项可以实现这种行为,我想再添加一个:
https://github.com/pydanny/cached-property

相关问题