在imp期间向类添加静态值

2024-10-01 07:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类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的实例时,它都已经有了这个预设。现在,我知道这不是我写的方式-但有什么接近吗


Tags: 文件path项目fromimportselfcachesys
3条回答

继承如何:

class ProcjetCacheHelper(cacheHelper):

    def __init__(self, fileName, attr=[], folder='../../cache_project/', sanitize=True):
        super().__init__(fileName=fileName, attr=attr, folder=folder, sanitize=sanitize)


helper = ProcjetCacheHelper('fn')
print(helper.folder)

输出:

../../cache_project/

当然,您可以相应地更改名称,这样您就可以继续到处写cacheHelper

from cache import cacheHelper as OriginalCacheHelper

class ProcjetCacheHelper(OriginalCacheHelper):

    def __init__(self, fileName, attr=[], folder='../../cache_project/', sanitize=True):
        super().__init__(fileName=fileName, attr=attr, folder=folder, sanitize=sanitize)

cacheHelper = ProcjetCacheHelper 

只需编写一个helper函数,用正确的默认值为您调用该函数:

def newCacheHelper (fileName, attr, sanitize=True, folder='../../cache/'):
    return cacheHelper(fileName, attr, folder, sanitize)

您甚至可以用新的替换现有的:

originalCacheHelper = cacheHelper
def cacheHelper (fileName, attr, sanitize=True, folder='../../cache/'):
    return originalCacheHelper(fileName, attr, folder, sanitize)

把它放到您自己的模块中并从那里导入cacheHelper,您不需要调整代码中的任何内容来使用正确的文件夹

首先,我建议再考虑一下这个问题;在大多数情况下,全局状态不是你需要的

在高层,您需要一个singleton

一方面,您可以在^{}方法中手工实现,但我不建议这样做。Python导入系统机器被大量缓存。也就是说,每个模块一次只存在一个实例(以及其中的所有类)。所以,如果您觉得确实需要这样的功能,可以将您的状态放在模块范围内,比如

_path = '../folder'
class Cache:
    def do_some(self, arg):
        return arg * _path

每个应用程序只需调用一次“cache\u module.\u path='../other'

另一种肮脏的方法是把这个路径放在类中,比如class属性

class Cache:
    path = '../folder'
    @classmethod
    def do_some(cls, arg):
        return arg * cls.path

每个应用程序一次,你用Cache.path = '../other'设置缓存。缓存类和缓存模块在每个python解释器的所有代码库中都是相同的

相关问题 更多 >