如何在 python 中的文件之间传递全局变量

How to pass global variables between files in python

我有一个在 linux 上运行的半大型 python 应用程序。我正在尝试设置它,以便我可以在程序启动时读取配置文件,然后在应用程序 运行 时保存这些值以供随时使用,而无需重新读取配置文件。

所以我试图在我的第一个模块 test.py 中加载一个 configValues class。并读取设置的值。然后在此示例中再次读取 test2.py.

中的值

我从来没有得到这些值。有人可以帮助我吗?

Config.py

class config():

    def __init__(self):
        configFile = File(myPath)
        if configFile.exist():
            myXML = str(configFile.openAndRead())

    def setupValues(self):
        configValues.color = self.getElement('color')

    def getElement(self, element):
        tree=et.fromstring(self.myXML)

        for el in tree.findall('head'):
            for ch in el.findall(element):
            return ch.text


class configValues():

    def __init__(self):
        global color

test.py

import config

class test():

    def __init__(self):
        configObj = config.Config()
        configVal = config.configValues()

        configObj.setupValues()
        print configVal.color

test2.py

import config

class test2():

    def __init__(self):
        configVal = config.configValues()

        print configVal.color

向您的 config.py 添加一个全局变量和一个函数。而不是在 test1.py 和 test2.py 中创建 configobj,您可以调用此函数来获取配置对象。

configobj = None

def getconfigobj():
  global configobj
  if not configobj:
    configObj = config.Config()
  return configobj

根据评论进行编辑。是否有类似以下帮助(对 class 使用单个实例)?:-

config.py

 class config():
        _instance = None
        def __new__(cls):
            if config._instance:
                return config._instance
            return super(config, cls).__new__(cls)


        def __init__(self, myPath):
            configFile = File(myPath)
            if configFile.exist():
                myXML = str(configFile.openAndRead())
            config._dict['instance'] = self

        def setupValues(self):
            self.color = self.getElement('color')

        def getElement(self, element):
            tree=et.fromstring(self.myXML)

            for el in tree.findall('head'):
                for ch in el.findall(element):
                return ch.text

test1.py

import config
class test():
    def __init__(self):
        configObj = config.Config()
        configObj.setupValues()
        print configObj.color

test2.py

import config
class test2():
    def __init__(self):
        configObj = config.Config()
        print configObj.color

在这种情况下我不会使用全局变量。您可能希望将配置值分配为配置属性并像这样使用它: config.py

class Config:
    def __init__(self):
        # property of the config class
        self.color = 'my default color'
        # open your config file ..

    def setup_values(self):
        # assign new value
        self.color = self.get_color()

    def get_color(self):
        # get values from config xml file ..
        return "red"

然后在其他模块中导入配置并调用颜色属性: main.py

from config import Config

class Main:
    def __init__(self):
        config = Config()
        config.setup_values()
        color = config.color
        print color

Main()

我还会通过在构造函数中获取配置值而不是在其他方法 "setup_values" 中获取配置值来减少一种方法的代码,如下所示:

class Config:
    def __init__(self):
        # property of the config class
        self.color = self.get_color()

    def get_color(self):
        # open your config file ..
        # get values from config xml file ..
        return "red"

并且 main.py 应该如下所示:

from config import Config

class Main:
    def __init__(self):
        config = Config()
        color = config.color
        print color

Main()

请记住,在您的代码中使用全局变量不是一个好习惯,因此上面建议的代码可能会为您完成这项工作。