我有一个主文件,我可以说main.py
生成一个对象列表(正文):
bodies = [body.Body(
number = i,
length = 1.,
mass = 10.,
mass_moment_of_inertia = 1.,
theta = 0.,
omega = 0.,
xy_force_vector = np.array([0., 0.]),
xy_u_F_vector = np.array([0., 0.]),
ground = 0,
limit_x = 0.,
limit_y = 0.,
z_moment = 0.,
stiffness_coef = 0.,
damping_coef = 0.)
for i in range(0, N)]
我想使用(多个)子文件/模块中的对象列表(主体)的属性来计算所需的值。我有模块submodule.py,它具有: submodule.py
def fun_name():
for i in range(0, N):
# joins mass of all objects in one array (this is just an example, I have to to more calculations with the object properties)
q = bodies[i].mass.append()
return q
答案 0 :(得分:2)
全局仅限于当前模块。而不是使用全局变量,将列表作为参数传递:
def fun_name(bodies):
# ...
并使用 定义全局的模块中的正文列表调用fun_name()
。
答案 1 :(得分:1)
@Martin Pieters的答案是最好的方法。为了完整起见,你也可以这样做:
from main import bodies
def fun_name():
# ...
无论哪种方式,最好明确说明python中的内容来源。
此外,我的示例假设main.py
可从submodule.py
导入。
答案 2 :(得分:1)
在main.py
中添加第import subprocess
行,而不是
打电话给你的功能
import subprocess
subprocess.fun_name(bodies) # after the definition of `bodies`
在subprocess.py
修改您的功能def fun_name(bodies):
两个文件都需要位于同一目录中才能轻松实现。