我有一个类cacheHelper
,我包括如下:
import sys
sys.path.append('../../../utilities/')
from cache import cacheHelper
稍后,在我的代码中,我使用此类访问缓存:
helper = cacheHelper(folder='../../cache/', fileName='fileName', attr=attrs)
与folder
有关的部分非常琐碎:
class cacheHelper():
def __init__(self, fileName, attr=[], folder='../cache/', sanitize=True):
# sanitize: round input numbers.
self.folder = folder
现在,每次我在我的项目中启动cacheHelper
,我都需要告诉它folder
它可以读/写的地方。我不能在构造函数中使用默认值,因为它不能是特定于项目的
一种方法是在我要缓存的每个函数中携带对cacheFolder
的引用,然后传递cacheHelper(folder=cacheFolder)
看起来很混乱。在包含文件的过程中,是否可以在文件级别执行某些操作
我梦想的解决办法是
from cache import cacheHelper(folder='../../cache')
,然后神奇地每次我使用cacheHelper
的实例时,它都已经有了这个预设。现在,我知道这不是我写的方式-但有什么接近吗
继承如何:
输出:
当然,您可以相应地更改名称,这样您就可以继续到处写
cacheHelper
:只需编写一个helper函数,用正确的默认值为您调用该函数:
您甚至可以用新的替换现有的:
把它放到您自己的模块中并从那里导入
cacheHelper
,您不需要调整代码中的任何内容来使用正确的文件夹首先,我建议再考虑一下这个问题;在大多数情况下,全局状态不是你需要的
在高层,您需要一个singleton
一方面,您可以在^{} 方法中手工实现,但我不建议这样做。Python导入系统机器被大量缓存。也就是说,每个模块一次只存在一个实例(以及其中的所有类)。所以,如果您觉得确实需要这样的功能,可以将您的状态放在模块范围内,比如
每个应用程序只需调用一次“cache\u module.\u path='../other'
另一种肮脏的方法是把这个路径放在类中,比如class属性
每个应用程序一次,你用
Cache.path = '../other'
设置缓存。缓存类和缓存模块在每个python解释器的所有代码库中都是相同的相关问题 更多 >
编程相关推荐