【问题标题】:python: How to monitor a variable ? Execute command when variable changepython:如何监控变量?变量变化时执行命令
【发布时间】:2023-03-08 00:12:02
【问题描述】:

我有这样的课


class WaveData(object):
    def __init__(self, data):
        self.data = data

并创建一个数据对象,绘制一个图形

wave = WaveData([[1, 2, 3], 
                 [7, 5, 6]])

import matplotlib.pyplot as plt
fig=plt.figure()
plot1, = fig.canvas.figure.subplots().plot(wave.data[0])
plot2, = fig.canvas.figure.subplots().plot(wave.data[1])

我希望当我改变波值时,情节会同步变化

wave.data[1]=[5,6,7] # hope figure change together

我尝试为WaveData 类添加方法changedata,但是:

  1. 它需要使用全局变量fig,可能不合理(我可以将fig作为self属性,但实际上fig还链接了其他没有写在这里的类对象)
  2. 我无法通过直接更改数据来更改fig:wave.data[1] =[5,6,7]
class WaveData(object):
    def __init__(self, data):
        self.data = data

    def changedata(self,value,index):
        self.data[index]=value
        

        #-- change the plot index th plot data--#
        global plot1,plot2,fig
        plot1.set_ydata(self.data[1])
        plot2.set_ydata(self.data[2])
        fig.canvas.draw_idle()
        #-- change the plot index th plot data--#
     

我想创建一个观察者来监控 wave.data 值。当检测到值变化时,执行一些动作

怎么办?

【问题讨论】:

    标签: python


    【解决方案1】:

    正确:绘图不是动态或交互的过程。您以正确的方式开始,使用更改波形的访问方法。现在您必须重新绘制并重新显示结果......这可能需要手动关闭第一个绘图,具体取决于您选择的绘图包的界面(例如matplotlib)。

    要获得完全互动的体验,您可能需要使用动画包,例如 PyGame,其中视觉显示的变化是包假设的一部分。

    【讨论】:

    • 我们不能利用properties set or get here的优势吗?
    • @mahesh 不容易不...假设您为.data 创建了一个吸气剂...那么用户仍然可以使用.data[0][0]=100 更改数据...所以现在您需要包装您要返回到陷阱的值 __setitem__ 等(必须包装它返回的值)等。
    猜你喜欢
    • 2019-04-17
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2014-08-27
    • 2014-08-30
    • 2013-01-05
    • 1970-01-01
    相关资源
    最近更新 更多