Caching class attributes in Python

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

提交回复
热议问题