簡體   English   中英

如何將對象列表作為全局變量傳遞給python中的模塊

[英]How to pass a list of objects as global variable to module in python

我有一個主文件,可以說main.py ,在其中生成對象( 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

全局變量僅限於當前模塊。 不要使用全局變量,而將列表作為參數傳遞:

def fun_name(bodies):
    # ...

並調用fun_name()與來自確實定義全球模塊的機構名單。

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

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

無論哪種方式,最好都明確說明python的來源。

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

main.pymain.py添加行import subprocess main.py ,然后調用函數

import subprocess

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

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

為了方便起見,兩個文件都必須位於同一目錄中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM