从不同包中的文件访问静态类变量

2024-03-28 21:24:44 发布

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

我的Python项目中有以下文件结构:

Main.py
classes
  |--- __init__.py
  |--- Common.py
  |--- Logger.py
  |--- Dictionary.py

我正在从Main文件中设置Common类的静态变量:

from classes.Common import Common

# set path to the log file for log output
Common.set_log_file_path(C:\\logging\\output.txt"))

Common类中设置:

class Common():
    log_file_path = ''

    @staticmethod
    def set_log_file_path(log_file_path):
        Common.log_file_path = log_file_path

现在,我从Main文件中实例化一个Logger对象:

from classes.Logger import Logger

# initiate logger
log = Logger()

Logger对象从通用对象读取日志文件路径,该路径工作正常:

from Common import Common

class Logger():
    log_file_path = ''

    def __init__(self, log_file_path=''):
        # if not specified, take default log file path from Common class
        if log_file_path == '':
            self.log_file_path = Common.log_file_path

现在问题来了:我从我的Main文件实例化了一个Dictionary对象:

from classes.Dictionary import Dictionary

# load dictionary
dictionary = Dictionary()

在dictionary对象中,我还希望有一个记录器,因此我在那里创建了一个记录器:

from Logger import Logger

class Dictionary():
    log = Logger()

    def __init__(self):
        Dictionary.log.info('Dictionary > __init__()')

但是这个不行。当字典中的记录器试图从Common类加载日志文件路径时,它是空的

为什么会这样?这不应该是相同的Common类,因此在这里保存相同的静态信息吗?我错过什么了吗?我是不是用错误的方式进口

我正在使用Python 2.6.5,导入内容如下:

Main.py imports Dictionary, Logger, Common
Dictionary.py imports Logger
Logger.py imports Common
Common has no imports

Tags: 文件path对象frompyimportlogdictionary
1条回答
网友
1楼 · 发布于 2024-03-28 21:24:44

Python模块中的几乎所有内容都是动态执行的,包括importclass语句

当您第一次导入Directory模块时,即执行导入Loggerimport语句,并在导入Logger之后执行class Directory:语句,该语句实例化Logger对象。此时尚未调用Common.set_log_file_path(),因此Logger对象采用执行class Common:时定义的默认值

“解决方案”将导入Common,并在执行任何实际使用默认路径属性的操作之前设置默认路径:

from classes.Common import Common
Common.log_file_path = 'C:/logging/output.txt'
from classes.Directory import Directory
from classes.Logger import Logger

由于导入依赖于之前执行的其他代码,所以很容易变成小噩梦,所以将解决方案置于引号中。因此,这在生产性代码中非常少见

相关问题 更多 >