【问题标题】:Accessing a static class variable from a file in a different package从不同包中的文件访问静态类变量
【发布时间】:2015-05-12 12:04:41
【问题描述】:

我的 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 对象从正常工作的 Common 对象读取日志文件路径:

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()

在字典对象中我也想有一个记录器,所以我在那里创建一个:

from Logger import Logger

class Dictionary():
    log = Logger()

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

但是这个不行。不知何故,当 Dictionary 中的 Logger 尝试从 Common 类加载日志文件路径时,它是空的。

为什么会这样?那不应该是相同的Common 类,因此在这里持有相同的静态信息吗?我错过了什么吗?我是否以错误的方式进行导入?

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

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

【问题讨论】:

  • 您是否在 导入Dictionary 之前设置了路径?依赖于导入顺序或期望某些代码在导入之前运行的代码是调试和维护的噩梦。还要确保您没有循环导入。拥有类级别的后备属性是一个不错的技巧,但恕我直言,这也正是:一个技巧。
  • 在任何其他代码之前,我都在顶部包含了 Java,因此我认为应该没问题。我在问题中添加了我的导入结构 - 也没有循环导入。

标签: python class static


【解决方案1】:

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

当您在第一次执行模块时导入Directory 模块时,这意味着导入Loggerimport 语句被执行,在Logger 被导入之后,class Directory: 被执行,它实例化了一个@ 987654328@ 对象。此时您的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

引号中的解决方案,因为根据之前执行的其他代码进行导入很容易变成小噩梦。因此,它在生产代码中很少见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多