在 python 个文件之间共享代码

Sharing code between python files

假设我有以下文件:

-- classes.py
-- main.py
-- commands.py
-- output.py

main.py 是使用 classescommandsoutput 代码的主文件。 commandsclasses 中定义的对象作为功能输入并访问这些对象的 methods/attributes。 commandsclasses 都使用 output.

中定义的函数

问题:我是否需要在依赖于它们的每个文件中导入这些模块中的每一个? 即:我是否需要在 classescommandsmain 中导入 output?或者 classesoutputcommands 都导入到 main 中是否意味着它们不需要单独导入?

处理具有相互依赖性的多个文件的最佳做法是什么?

The question: do I need to import each of these modules in each of the files that depend on them? i.e.: do I need to import output in both classes, commands, and main?

是的,这是要走的路。

Or would the fact that classes, output, and commands are all imported into main mean that they don't need to be imported individually?

没有

Python 文件是模块。 python 模块有一个符号 table。模块中指定的每个函数,class和变量都在这个table中。一个模块只能使用这个 table 加上 Python 内置的东西。

例如 classes.py:

def function(): pass
class Class(object): pass

有符号table:

{
    'function': function,
    'Class': Class
}

您只能在 classes.py 中使用 functionClass(加上提到的内置函数)。您不能隐式访问此模块之外的任何内容,Python 没有像 C# 和 Java 那样的任何命名空间概念。如果您需要来自不同文件(模块)的任何内容,则必须显式导入它。

现在当你 "import" 时到底发生了什么?

一些非常简单的东西 - 导入的模块 "becomes" 模块本身的一部分!

在下一个例子中我们有 output.py:

def output_function(): pass

带符号 table:

{
    'output_function': output_function
}

classes.py

import output
from output import output_function

def function(): pass
class Class(object): pass

带符号 table:

{
    'Class': Class,
    'function': function,
    'output': {
        'output_function': output_function
    }
    'output_function': output_function
}

其中 'output' 的值实际上是 'output' 的符号 table(完全相同的对象)!

你甚至可以在不同的模块中做:

import classes

classes.output.output_function()

但是不要,明确说明你的导入。

这听起来可能有点奇怪,但这就是 Python 的工作原理。请注意,涉及的内容更多,例如,当您第一次导入模块时,它会被执行等等...