gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:05:11 25 4
gpt4 key购买 nike

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

上下文:我有一个父类,其中包含一些用于多个子类的通用代码(加载配置文件、构建 ssh 连接等)。其中之一是模块类,它设置模块,因此使用 ssh 连接和配置文件等。我的目标是与将要设置的下一个模块共享配置文件和连接。对于连接来说,一直构建和销毁它只是一种浪费,但是对于配置文件来说,设置过程中的更改可能会导致未定义的行为。

研究/方法:

  • 我尝试使用类变量,但是在初始化时它们没有被传递一个新的模块对象。

  • 此外,我尝试使用全局变量,但是由于父类和子类位于不同的文件中,这行不通(是的,我可以将它们全部都在一个文件中,但这会一团糟)还使用来自的 getter 函数我定义全局变量的文件不起作用。

  • 我知道“内置”解决方案 How to make a cross-module variable?变量,但感觉这有点过分了...

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

这里有一些带有示例方法的代码,用于获取一些文件路径。代码按照方法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

关于python - 在新对象实例之间共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55457553/

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