关于Python局部变量的数据获取

问题遇到的现象和发生背景

我在学习软件包的代码过程中,想要获取到迭代过程中的变化数据,发现变量是在函数里的局部变量,在调用这个模块的时候,外部无法获取到这个变量的具体数据。

问题相关代码,请勿粘贴截图
f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,3))

simulation.plt_eps(ax=ax1, outline=False)
ax1.set_title('final permittivity distribution')

optimization.plt_objs(ax=ax2)
ax2.set_yscale('linear')

(_,_,Ez) = simulation.solve_fields()
simulation.plt_abs(ax=ax3, vmax=None)
ax1.set_title('linear field')

plt.show()

以上是外部的代码,调用optimization模块中的plt_objs

def plt_objs(self, norm=None, ax=None):
        """ Plots objective function vs. iteration"""

        iter_range = range(1, len(self.objfn_list) + 1)
        if norm == 'field':
            obj_scaled = [o/a for o, a in zip(self.objfn_list, self.src_amplitudes)]
            ax.set_ylabel('objective function / field')
        elif norm == 'power':
            obj_scaled = [o/a**2 for o, a in zip(self.objfn_list, self.src_amplitudes)]
            ax.set_ylabel('objective function / power')
        else:
            obj_scaled = self.objfn_list
            ax.set_ylabel('objective function')

        ax.plot(iter_range,  obj_scaled)
        ax.set_xlabel('iteration number')
        ax.set_title('optimization results')
        return ax

以上是optimization模块中的函数定义

我想获取到这里面obj_scaled的具体值然后导入Excel用origin画个图。

运行结果及报错内容

不管怎么加定义和参数设置,一直是未定义,无法调用

我的解答思路和尝试过的方法

在模块中增加全局变量的定义,无效

我想要达到的结果

仅仅只是想获取obj_scaled的数值,应该是一个list

最简单的是在 plt_objs()函数中 return obj_scaled 返回 obj_scaled
调用时obj_scaled = optimization.plt_objs(ax=ax2) 接收返回值

或者是在 plt_objs()函数中用global obj_scaled 把obj_scaled声明为全局变量

def plt_objs(self, norm=None, ax=None):
    """ Plots objective function vs. iteration"""
    global obj_scaled

    iter_range = range(1, len(self.objfn_list) + 1)
    if norm == 'field':
        obj_scaled = [o/a for o, a in zip(self.objfn_list, self.src_amplitudes)]
        ax.set_ylabel('objective function / field')
    elif norm == 'power':
        obj_scaled = [o/a**2 for o, a in zip(self.objfn_list, self.src_amplitudes)]
        ax.set_ylabel('objective function / power')
    else:
        obj_scaled = self.objfn_list
        ax.set_ylabel('objective function')

    ax.plot(iter_range,  obj_scaled)
    ax.set_xlabel('iteration number')
    ax.set_title('optimization results')
    return ax

调用optimization.plt_objs(ax=ax2)之后
再获取optimization模块中的全局变量obj_scaled
print(optimization.obj_scaled)

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632