Caching class attributes in Python

后端 未结 9 1053
暖寄归人
暖寄归人 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:15

    With Python 2, but not Python 3, here's what I do. This is about as efficient as you can get:

    class X:
        @property
        def foo(self):
            r = 33
            self.foo = r
            return r
    

    Explanation: Basically, I'm just overloading a property method with the computed value. So after the first time you access the property (for that instance), foo ceases to be a property and becomes an instance attribute. The advantage of this approach is that a cache hit is as cheap as possible because self.__dict__ is being used as the cache, and there is no instance overhead if the property is not used.

    This approach doesn't work with Python 3.

提交回复
热议问题