简体   繁体   中英

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:

  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)
  2. I cannot change fig by changing data directly: 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--#
     

I want to create a watcher to monitor wave.data value . 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 ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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