0

I have never seen this use before, in the following code, there is a definition data_gen.t = 0, data_gen is not a class, looks we could use function as prefix and define the variable as fun.*, what is the point here? I use a different definition such as xx = 0 instead of data_gen.t = 0, and replace t = data_gen.t with t = xx, everything works well.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def data_gen():
    t = data_gen.t
    cnt = 0
    while cnt < 1000:
        cnt+=1
        t += 0.05
        yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
data_gen.t = 0

fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 5)
ax.grid()
xdata, ydata = [], []
def run(data):
    # update the data
    t,y = data
    xdata.append(t)
    ydata.append(y)
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    return line,

ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,
    repeat=False)
plt.show()
martineau
  • 119,623
  • 25
  • 170
  • 301
adam wu
  • 47
  • 5
  • 3
    `datagen` is a function, functions are objects like any other, and you *can* assign attributes to those objects* just like most objects. Whether that is a good design decision is another question, but it is possible and very mundane and not mysterious. Note, the function name isn't anything special, it is just a regular variable. You could do `foo = data_gen` and now `foo` refers to your function, just like `data_gen`, just like if you do `a = []; b = a` not `a` and `b` both refer to the same list object. – juanpa.arrivillaga Apr 14 '20 at 00:21
  • 3
    It's equivalent to using a global variable like `data_gen_t`, but it doesn't pollute the global variable namespace. – Barmar Apr 14 '20 at 00:24
  • See [Access a function variable outside the function without using “global”](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global). – martineau Apr 14 '20 at 00:41
  • 1
    It's usually better to use a class and have `data_gen` be a method, or have a function that returns a closure over `t`, though, than to save persistent data as a `function` attribute. – chepner Apr 14 '20 at 00:50
  • thanks for all your guys' comments, It looks it behaves exactly like a global variable. Barmar, when you say " it doesn't pollute the global variable namespace", what do you mean? – adam wu Apr 14 '20 at 04:52

0 Answers0