[英]How to redefine a varying variable in a function from outside?
To do a sensitivity-analsysis on some of the parameters in my model, I want to overwrite and redefine a single variable.为了对我的 model 中的一些参数进行灵敏度分析,我想覆盖并重新定义一个变量。 This variable can be handpicked by the user.
这个变量可以由用户手动选择。 I cannot get the overwriting to work.
我无法让覆盖工作。
For now, I have focussed mainly on getting the locals() or globals() to the right value, but as shown below.目前,我主要关注将 locals() 或 globals() 设置为正确的值,但如下所示。 this did not work.
这没有用。
Two important parts of my code: first the Main function, doing all the work to create the model.我的代码的两个重要部分:首先是主 function,完成所有工作以创建 model。 It has many variables, one is shown: the Wave_height
它有很多变量,如图所示:Wave_height
def Main(loopname, loopvalue = 0):
Wave_height = 2 #m
# And_many_other_characteristics
# redefine one single variable name
vars()[loopname] = loopvalue
globals()[loopname] = loopvalue
locals()[loopname] = loopvalue
print (Wave_height)
return_info = 1 ## rows of code i dont want to bother you with ##
return(return_info)
if __name__ == "__main__":
Main("testname", 0)
For the sensitivity analysis, I would like to have all variables constant, except for a single variable.对于敏感性分析,我希望所有变量都保持不变,除了一个变量。 Lets assume I want to vary the Wave_height.
假设我想改变 Wave_height。 I want to do something like the following code:
我想做类似以下代码的事情:
import Main
import numpy as np
loopname = "Wave_height"
loopvalue = [1,2,3]
max_z_displacement = np.zeros(len(loopvalue))
for i in range (len(loopvalue)):
return_info = Main.Main(loopname, loopvalue[i])
max_z_displacement[i] = return_info[2]
Currently, the prints are as follows:目前,印刷品如下:
2
I would like to have the result being:我希望结果是:
1
I would like to avoid using 50 different variables in the def-row, as that would not make it easy to use.我想避免在 def-row 中使用 50 个不同的变量,因为这不会使它易于使用。
To make the called function look natural, pack the parameters in an otherwise featureless object:为了使调用的 function 看起来自然,将参数打包到其他没有特征的 object 中:
class Parameters(object):
def __init__(self,**attr): vars(self).update(attr)
def calc(**over):
p=Parameters(Wave_height=2,…)
vars(p).update(over)
do_stuff(p.Wave_height,…)
do_more(p.other_data)
…
for h in heights:
calc(Wave_height=h)
calc(**{"Wave_height":h}) # to choose parameter dynamically
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.