我有一个代码,我希望拆分成多个文件.在matlab中,可以简单地调用一个.m
文件,只要它没有特别定义为任何东西,它就会像被调用的代码一样运行.示例(已编辑):
test.m(matlab)
function [] = test()
... some code using variables ...
test2
Run Code Online (Sandbox Code Playgroud)
test2.m(matlab)
... some more code using same variables ...
Run Code Online (Sandbox Code Playgroud)
调用test
运行test中的代码以及test2中的代码.
是否有类似的方式将python放入... some more code ...
外部文件中,只需将其读取就好像它在调用它的文件中一样?
mgi*_*son 57
当然!
#file -- test.py --
myvar = 42
def test_func():
print("Hello!")
Run Code Online (Sandbox Code Playgroud)
现在,这个文件("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
Run Code Online (Sandbox Code Playgroud)
通过使用__init__.py
允许您将多个文件视为单个模块的特殊文件,您可以做更多的事情,但这回答了您的问题,我想我们将把剩下的时间留下来.
小智 36
我刚刚在python中研究模块的使用,并且我认为我会回答Markus在上面的评论中提出的问题("如何在嵌入模块时导入变量?")从两个角度来看:
以下是我将如何重写主程序f1.py以演示Markus的变量重用:
import f2
myStorage = f2.useMyVars(0) # initialze class and properties
for i in range(0,10):
print "Hello, "
f2.print_world()
myStorage.setMyVar(i)
f2.inc_gMyVar()
print "Display class property myVar:", myStorage.getMyVar()
print "Display global variable gMyVar:", f2.get_gMyVar()
Run Code Online (Sandbox Code Playgroud)
以下是我将如何重写可重用模块f2.py:
# Module: f2.py
# Example 1: functions to store and retrieve global variables
gMyVar = 0
def print_world():
print "World!"
def get_gMyVar():
return gMyVar # no need for global statement
def inc_gMyVar():
global gMyVar
gMyVar += 1
# Example 2: class methods to store and retrieve properties
class useMyVars(object):
def __init__(self, myVar):
self.myVar = myVar
def getMyVar(self):
return self.myVar
def setMyVar(self, myVar):
self.myVar = myVar
def print_helloWorld(self):
print "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
当执行f1.py时,输出结果如下:
%run "f1.py"
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Display class property myVar: 9
Display global variable gMyVar: 10
Run Code Online (Sandbox Code Playgroud)
我认为马库斯的观点是:
Ali*_*har 21
Python有导入和命名空间,这很好.在Python中,您可以导入到当前名称空间,如:
>>> from test import disp
>>> disp('World!')
Run Code Online (Sandbox Code Playgroud)
或者使用命名空间:
>>> import test
>>> test.disp('World!')
Run Code Online (Sandbox Code Playgroud)
您可以通过简单地导入第二个文件在 python 中执行相同的操作,导入时将运行顶层的代码。我建议这充其量是混乱的,而不是一个好的编程习惯。您最好将代码组织成模块
例子:
F1.py:
print "Hello, "
import f2
Run Code Online (Sandbox Code Playgroud)
F2.py:
print "World!"
Run Code Online (Sandbox Code Playgroud)
运行时:
python ./f1.py
Hello,
World!
Run Code Online (Sandbox Code Playgroud)
编辑澄清:我建议的部分是“混乱”,该import
语句仅用于生成输出的副作用,而不是创建单独的源文件。
归档时间: |
|
查看次数: |
125316 次 |
最近记录: |