Python class member lazy initialization

前端 未结 5 2081
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:18

    Ring gives lru_cache-like interface but working with any kind of descriptor supports: https://ring-cache.readthedocs.io/en/latest/quickstart.html#method-classmethod-staticmethod

    class Page(object):
        (...)
    
        @ring.lru()
        @classmethod
        def class_content(cls):
            return cls.base_content
    
        @ring.lru()
        @staticmethod
        def example_dot_com():
            return requests.get('http://example.com').content
    

    See the link for more details.

提交回复
热议问题