简体   繁体   English

python:如何监控变量? 变量改变时执行命令

[英]python: How to monitor a variable ? Execute command when variable change

I have a class like this我有一堂这样的课


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

and create a data object, plot a figure并创建一个数据对象,绘制一个图形

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])

I hope when I change the wave value , plot will change synchronously我希望当我改变波值时,情节会同步变化

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

I try to add method changedata for WaveData class, but:我尝试为WaveData类添加方法changedata ,但是:

  1. it need use global variable fig , maybe not reasonale (I can put fig as self attribute , but in fact , the fig also link other class object which not written in here)它需要使用全局变量fig ,可能不合理(我可以把 fig 作为 self 属性,但实际上, fig 还链接了其他没有写在这里的类对象)
  2. I cannot change fig by changing data directly: wave.data[1] =[5,6,7]我不能通过直接改变数据来改变figwave.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--#
     

I want to create a watcher to monitor wave.data value .我想创建一个观察者来监视wave.data值。 When detecte the value change , execute some action当检测到值变化时,执行一些操作

How to do?怎么做?

Right: plotting is not a dynamic or interactive process.右图:绘图不是一个动态的或交互式的过程。 You started the right way, with an access method to change the wave form.您以正确的方式开始,使用访问方法来更改波形。 Now you have to re-plot and re-show the result ... which will possibly require closing the first plot manually, depending on the interface of your chosen drawing package (eg matplotlib ).现在您必须重新绘制并重新显示结果......这可能需要手动关闭第一个绘图,具体取决于您选择的绘图包(例如matplotlib )的界面。

To get a fully interactive experience, you may want to use an animation package, such as PyGame, where changes in the visual display are part of the package assumptions.要获得完全交互的体验,您可能需要使用动画包,例如 PyGame,其中视觉显示的变化是包假设的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM