在新对象实例之间共享变量

卢卡斯

背景: 我正在编写一个模块以设置嵌入式系统。在这种情况下,我需要加载一些模块并执行一些系统设置。

上下文:我有一个父类,其中包含一些用于几个子类的通用代码(加载配置文件,建立ssh连接等)。其中之一是设置模块的模块类,因此除其他外还使用ssh连接和配置文件。我的目标是与下一个要共享的模块共享配置文件和连接。对于连接而言,这一直都是浪费时间来构建和销毁它,但是对于配置文件,安装过程中的更改可能导致不确定的行为。

研究/方法:

  • 我尝试使用类变量,但是在初始化新模块对象时未传递它们。

  • 此外,我尝试使用全局变量,但是由于父类和子类位于不同的文件中,因此无法正常工作(是的,我可以将它们全部放在一个文件中,但这将是一团糟)。从我定义全局变量的文件中无法正常工作。

  • 我知道如何制作跨模块变量中的“内置”解决方案可变的,但是觉得这有点矫kill过正...

  • 最后,我可以将配置文件和连接保留在中央脚本中,并将它们传递给每个实例,但这会导致大量的依赖关系,我认为这不是一个好的解决方案。

因此,这里有一些示例方法的代码,以获取一些文件路径。代码是根据方法1设置的(类可用)

配置文件示例:

Files:
  Core:
    Backend:
      - 'file_1'
      - 'file_2'
Local:
  File_path:
    Backend: '/the/path/to'

setup_class.py中的父类

import os
import abc
import yaml

class setup(object):
    __metaclass__ = abc.ABCMeta
    configuration = []

    def check_for_configuration(self, config_file):
        if not self.configuration:
            with open(config_file, "r") as config:
                self.configuration = yaml.safe_load(config)

    def get_configuration(self):
        return self.configuration

    def _make_file_list(self, path, names):
        full_file_path = []
        for file_name in names:
            temp_path = path + '/' + file_name
            temp_path = temp_path.split('/')
            full_file_path.append(os.path.join(*temp_path))
        return full_file_path

    @abc.abstractmethod
    def install(self):
        raise NotImplementedError

module_class.py中的模块类

from setup_class import setup

class module(setup):
    def __init__(self, module_name, config_file = ''):
        self.name = module_name
        self.check_for_configuration(config_file)

    def install(self):
        self._backend()

    def _backend(self):
        files = self._make_file_list(
                    self.configuration['Local']['File_path']['Backend'],
                    self.configuration['Files'][self.name]['Backend'])
        if files:
            print files

最后是一个测试脚本:

from module_class import module
Analysis = module('Analysis',"./example.yml")
Core = module('Core', "./example.yml")
Core.install()

现在,在运行代码时,每次都会加载配置文件,并初始化一个新的模块对象。我想避免这种情况。有没有我考虑过的方法?实现这一目标的最简洁的方法是什么?

吃东西

将全局值保存在全局字典中,并在模块内部进行引用。

cache = {}

class Cache(object):
    def __init__(self):
        global cache
        self.cache = cache

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章