Caching class attributes in Python

后端 未结 9 1014
暖寄归人
暖寄归人 2020-11-30 22:05

I\'m writing a class in python and I have an attribute that will take a relatively long time to compute, so I only want to do it once. Also, it will not be

相关标签:
9条回答
  • 2020-11-30 22:33

    You could try looking into memoization. The way it works is that if you pass in a function the same arguments, it will return the cached result. You can find more information on implementing it in python here.

    Also, depending on how your code is set up (you say that it is not needed by all instances) you could try to use some sort of flyweight pattern, or lazy-loading.

    0 讨论(0)
  • 2020-11-30 22:36
    class MemoizeTest:
    
          _cache = {}
          def __init__(self, a):
              if a in MemoizeTest._cache:
                  self.a = MemoizeTest._cache[a]
              else:
                  self.a = a**5000
                  MemoizeTest._cache.update({a:self.a})
    
    0 讨论(0)
  • 2020-11-30 22:36

    The dickens package (not mine) offers cachedproperty, classproperty and cachedclassproperty decorators.

    To cache a class property:

    from descriptors import cachedclassproperty
    
    class MyClass:
        @cachedclassproperty
        def approx_pi(cls):
            return 22 / 7
    
    0 讨论(0)
提交回复
热议问题