Python class member lazy initialization

前端 未结 5 2089
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:14

    Consider the pip-installable Dickens package which is available for Python 3.5+. It has a descriptors package which provides the relevant cachedproperty and cachedclassproperty decorators, the usage of which is shown in the example below. It seems to work as expected.

    from descriptors import cachedproperty, classproperty, cachedclassproperty
    
    class MyClass:
        FOO = 'A'
    
        def __init__(self):
            self.bar = 'B'
    
        @cachedproperty
        def my_cached_instance_attr(self):
            print('Initializing and caching attribute, once per class instance.')
            return self.bar * 2
    
        @cachedclassproperty
        def my_cached_class_attr(cls):
            print('Initializing and caching attribute, once per class.')
            return cls.FOO * 3
    
        @classproperty
        def my_class_property(cls):
            print('Calculating attribute without caching.')
            return cls.FOO + 'C'
    

提交回复
热议问题