在Python中只初始化一次字段

Vit*_*nov 7 python static

我有文件services.py,其中包含某些类MyCache.MyCache的所有实例都应共享一个"缓存"字段,因此我将其设置为静态.为了初始化缓存,有一个加载它的静态方法.在应用程序的最开始,这个方法只调用一次.

问题是,当我从其他.py文件导入services.py并创建MyCache实例时 - 它打印出该缓存是空的!

如何修复它并使类的所有实例共享"缓存"字段而忽略它们的创建位置?

我不明白为什么会这样.请帮忙 :)

services.py:

class MyCache:
    cache = {}

    @staticmethod
    def initialize():
       MyCache.cache = load_from_file()
       print(len(MyCache.cache)) # prints 3

    def __init__(self):
       print(len(MyCache.cache)) # supposed to print 3, because initialize has been called earlier, but prints 0 when called from other_file.py
Run Code Online (Sandbox Code Playgroud)

main.py:

import services

if __name__ == '__main__':
    services.MyCache.initialize()
Run Code Online (Sandbox Code Playgroud)

other_file.py:

import services

services.MyCache().foo() # creates instance, prints 0 in MyCache.__init__
Run Code Online (Sandbox Code Playgroud)

gni*_*las 1

#mycache.py
def load_from_file():
    pass
    ...
cache = load_from_file()

#anotherlib.py
from mycache import cache

...

#main.py
from anotherlib import ... #(Now the cache is initialized)
from mycache import cache #(Python looksup the mycache module and doesn't initialize it again)
Run Code Online (Sandbox Code Playgroud)

这里我们只是使用 python 模块作为单例。要了解有关 python 如何缓存模块以便仅初始化一次的更多信息,请阅读此处:https: //docs.python.org/2/library/sys.html#sys.modules