如果我在一个主文件中包含两个文件,我可以在第二个文件中使用第一个包含文件的函数吗

2024-04-20 05:31:02 发布

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

我有一个main.py文件

在这里我导入了另外两个文件。 第一个是包含一系列名为debug.py的调试函数的模块。 第二个只包含一个类定义

我希望我的调试函数可以从类中调用

我不想在我的类文件中导入debug.py,因为它有可配置的选项,我不想在程序中多次设置这些选项

这可能吗?我该怎么做

下面是一个非常简单的代码示例

主.py:

import debug
from class import CLASS

debug.debug_messages_enabled = True

my_object = CLASS()

调试.py:

debug_messages_enabled = False

def log (message):
    if debug_messages_enabled:
        output = ""
        output += "[LOG]: " 
        output += message
        print output

类.py:

class CLASS (object):
    def __init__ ():
        #I want to be able to access debug.log here

Tags: 文件函数pydebugimportlogmessageoutput
1条回答
网友
1楼 · 发布于 2024-04-20 05:31:02

您需要导入类文件中的debug.py

main.py对调试模块中的一个设置进行更改的事实与此无关。您的类文件将包含调试语句、进行调试调用等

打印/不打印的决定将基于该设置。设置(debug_messages_enabled)将由main.py更改,但这与class.py无关

类.py:

from debug import log

class CLASS (object):
    def __init__ (self):
        log("A long thick section of trimmed, unhewn timber.")
        self.foo = 1

相关问题 更多 >