Python class member lazy initialization

前端 未结 5 2077
Happy的楠姐
Happy的楠姐 2021-02-01 18:37

I would like to know what is the python way of initializing a class member but only when accessing it, if accessed. I tried the code below and it is working but is there somethi

5条回答
  •  隐瞒了意图╮
    2021-02-01 19:20

    This answer is for a typical instance attribute/method only, not for a class attribute/classmethod, or staticmethod.

    For Python 3.8+, how about using the cached_property decorator? It memoizes.

    from functools import cached_property
    
    class MyClass:
    
        @cached_property
        def my_lazy_attr(self):
            print("Initializing and caching attribute, once per class instance.")
            return 7**7**8
    

    For Python 3.2+, how about using both property and lru_cache decorators? The latter memoizes.

    from functools import lru_cache
    
    class MyClass:
    
        @property
        @lru_cache()
        def my_lazy_attr(self):
            print("Initializing and caching attribute, once per class instance.")
            return 7**7**8
    

    Credit: answer by Maxime R.

提交回复
热议问题