python - 将python源代码拆分为多个文件?

标签 python

我有一个代码,我希望将其拆分为多个文件。在 matlab 中,可以简单地调用一个 .m 文件,只要它没有被特别定义为任何东西,它就会像被调用代码的一部分一样运行。示例(已编辑):
test.m (matlab)

function [] = test()
    ... some code using variables ...
    test2

test2.m (matlab)

... some more code using same variables ...

调用 test 运行 test 中的代码以及 test2 中的代码。

python 是否有类似的方法,将 ...更多代码 ... 放入外部文件中,就像在文件中一样简单地读取它从?

最佳答案

当然!

#file  -- test.py --
myvar = 42
def test_func():
    print("Hello!")

现在,这个文件(“test.py”)在 python 术语中是一个“模块”。我们可以导入它(只要可以在我们的PYTHONPATH中找到)注意当前目录总是在PYTHONPATH中,所以如果use_test正在从 test.py 所在的同一目录运行,您已准备就绪:

#file -- use_test.py --
import test
test.test_func()  #prints "Hello!"
print (test.myvar)  #prints 42

from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar)     #Exception (NameError)

from test import *
test_func() #prints "Hello"
print(myvar)      #prints 42

您可以做的不仅仅是通过使用特殊的 __init__.py 文件,这些文件允许您将多个文件视为一个模块),但这回答了您的问题,我想我们将剩下的时间再离开。

关于python - 将python源代码拆分为多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12412595/

相关文章:

python - 使用 ThreadPoolExecutor 时记录线程

python - 快速 n-gram 计算

python - 访问所有函数参数

python - 如何顺序查找文件并保存?

python - 在元组 Python 中查找模式

python - PyQt5 调整应用程序大小以适应不同的显示器

python - 有没有办法将多种日期格式转换为日期时间python

Python Reportlab 合并段落

python - 高斯过程算法出错,numpy 内存问题?

python - 有没有一种更简单的方法可以将列表随机拆分为子列表而无需在 python 中重复元素?