gpt4 book ai didi

python - 处理大量变量并将其传递给 python 中的函数\对象

转载 作者:行者123 更新时间:2023-11-28 20:09:54 25 4
gpt4 key购买 nike

我发现自己需要处理带有大量变量的函数和对象。

对于特定情况,考虑来自分离模块的函数,该函数采用 N 个不同的变量,然后将它们传递给新实例化的对象:

def Function(Variables): 
Do something with some of the variables
object1 = someobject(some of the variables)
object2 = anotherobject(some of the variables, not necessarily as in object1)

虽然我只能传递一长串变量,但有时我发现自己对一个函数进行更改,这需要更改它可能调用的其他函数或它可能创建的对象。有时变量列表可能会稍微改变。

是否有一种优雅的方式来传递大量变量并保持灵 active ?

我尝试通过以下方式使用 kwargs:

def Function(**kwargs):

Rest of the function

并调用 Function(**somedict),其中 somedict 是一个字典,其中包含我需要传递给 Function 的所有变量的键和值(也许还有更多)。但是我收到有关未定义的全局变量的错误。

编辑1:

我稍后会发布这段代码,因为我现在不在家或实验室。到那时我会尝试更好地解释情况。

我有一个分子动力学模拟,它需要几十个参数。很少有参数(例如温度)需要迭代。为了充分利用四核处理器,我并行运行了不同的迭代。因此,代码从不同迭代的循环开始,并在每次传递时将该迭代的参数发送到工作池(使用多处理模块)。它是这样的:

P = mp.pool(number of workers) # If i remember correctly this line 
for iteration in Iterations:
assign values to parameters
P.apply_async(run,(list of parameters),callback = some post processing)
P.close()
P.join()

函数 run 获取参数列表并生成模拟对象,每个对象都将一些参数作为其属性。

编辑2:

这是有问题的函数的一个版本。 **kwargs 包含“sim”、“lattice”和“adatom”所需的所有参数。

def run(**kwargs): 
"""'run' runs a single simulation process.
j is the index number of the simulation run.
The code generates an independent random seed for the initial conditios."""
scipy.random.seed()
sim = MDF.Simulation(tstep, temp, time, writeout, boundaryxy, boundaryz, relax, insert, lat,savetemp)
lattice = MDF.Lattice(tstep, temp, time, writeout, boundaryxy, boundaryz, relax, insert, lat, kb, ks, kbs, a, p, q, massL, randinit, initvel, parangle,scaletemp,savetemp,freeze)
adatom = MDF.Adatom(tstep, temp, time, writeout, boundaryxy, boundaryz, relax, insert, lat, ra, massa, amorse, bmorse, r0, z0, name, lattice, samplerate,savetemp,adatomrelax)

bad = 1
print 'Starting simulation run number %g\nrun' % (j+1)
while bad is 1:
# If the simulation did not complete successfuly, run it again.
bad = sim.timeloop(lattice,adatom1,j)
print 'Starting post processing'
# Return the temperature and adatomś trajectory and velocity
List = [j,lattice.temp , adatom1.traj ,adatom1.velocity, lattice.Toptemp, lattice.Bottomtemp, lattice.middletemp, lattice.latticetop]
return List

最佳答案

最干净的解决方案是根本不在一个函数中使用那么多参数。

您可以使用 set 方法或属性分别设置每个变量,将它们存储为类成员并由该类中的函数使用。

这些函数填充私有(private)变量,get 方法可用于检索这些变量。

另一种方法是使用结构(或没有函数的类),这样可以创建一组命名的变量。

关于python - 处理大量变量并将其传递给 python 中的函数\对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9631937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com