Python - Lazy loading of class attributes

前端 未结 3 1528
自闭症患者
自闭症患者 2020-12-08 10:42

Class foo has a bar. Bar is not loaded until it is accessed. Further accesses to bar should incur no overhead.

class Foo(object):

    def get_bar(self):
            


        
3条回答
  •  误落风尘
    2020-12-08 11:17

    Sure it is, try:

    class Foo(object):
        def __init__(self):
            self._bar = None # Initial value
    
        @property
        def bar(self):
            if self._bar is None:
                self._bar = HeavyObject()
            return self._bar
    

    Note that this is not thread-safe. cPython has GIL, so it's a relative issue, but if you plan to use this in a true multithread Python stack (say, Jython), you might want to implement some form of lock safety.

提交回复
热议问题