2013-05-28 44 views
0

到模塊我有一個主文件可以說main.py在哪裏產生的對象(機構)名單:如何傳遞對象作爲全局變量列表在python

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

謝謝大家的幫助。現在我必須考慮什麼是我的問題的最佳解決方案。再次感謝! – avstenit

回答

1

@Martin Pieters的答案是做到這一點的最佳方式。爲了完整起見,你也可以這樣做:

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

無論哪種方式,最好是明確的事情來自於python。

此外,我的示例假定main.py可從submodule.py導入。

+0

基於此,您可以動態創建一個模塊並在需要時將其導入。 –

2

全局僅限於當前模塊。而不是使用全局變量,通過在列表中作爲一個參數:

def fun_name(bodies): 
    # ... 

,並呼籲fun_name()從模塊定義全局的機構名單。

1

main.py在開始添加行import subprocess,比 調用函數

import subprocess 

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

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

兩個文件都必須在同一個目錄,以方便。