gpt4 book ai didi

python - 在 Python 中仅初始化一次字段

转载 作者:太空狗 更新时间:2023-10-30 00:13:15 25 4
gpt4 key购买 nike

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

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

我怎样才能修复它并使“缓存”字段由类的所有实例共享而不管它们的创建位置?

我不明白为什么会这样。请帮助:)

服务.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

主要.py:

import services

if __name__ == '__main__':
services.MyCache.initialize()

其他文件.py:

import services

services.MyCache().foo() # creates instance, prints 0 in MyCache.__init__

最佳答案

#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)

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

关于python - 在 Python 中仅初始化一次字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41402789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com