0

我有一个主文件,可以说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
4

3 回答 3

1

全局变量仅限于当前模块。不使用全局变量,而是将列表作为参数传递:

def fun_name(bodies):
    # ...

从定义全局的模块中调用fun_name()您的身体列表。

于 2013-05-28T12:44:44.460 回答
1

@Martin Pieters 的回答是最好的方法。不过,为了完整起见,您也可以这样做:

from main import bodies
def fun_name():
    # ...

无论哪种方式,最好明确说明python中事物的来源。

此外,我的示例假设可以main.pysubmodule.py.

于 2013-05-28T12:48:00.783 回答
1

在开头main.py添加行,然后调用您的函数import subprocess

import subprocess

subprocess.fun_name(bodies) # after the definition of `bodies`

subprocess.py修改你的功能def fun_name(bodies):

这两个文件需要在同一个目录中才能方便。

于 2013-05-28T12:51:50.973 回答