python - 为什么保存未使用的变量会产生影响?

标签 python python-3.x matplotlib garbage-collection

我在使用 matplotlib 时发现了这种奇怪而有趣的行为。 我写了一个简单的动画用于演示目的:

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


fig, ax = plt.subplots()
line, = ax.plot(range(10))


def func(i=0):
    line.set_ydata(np.random.rand(10) * 10)
    return line


ani = animation.FuncAnimation(
    fig=fig,
    func=func,
    frames=np.linspace(0, 4 * np.pi, 300),
)
plt.show()

它按预期工作,没有发生任何奇怪的事情。

但是如果我将行更改为:

animation.FuncAnimation(
    fig=fig,
    func=func,
    frames=np.linspace(0, 4 * np.pi, 300),
)

它停止工作,并且 func 永远不会被调用。

那么,为什么保存 ani 对象会产生差异,即使它从未被引用? matplotlib 如何知道我是否这样做了?

================

我刚写完这篇文章,垃圾收集器就在我的脑海中浮现出来。但我不知道 gc 是如何工作的,并且多次测试并没有说服我。

此外,我想知道:

类似的行为在其他库中是否常见? 我认为我们调用函数要么是为了“某些东西”,要么是为了“获取返回的值或对象”,所以 FuncAnimation 对我来说似乎很奇怪。我的感觉对吗?

最佳答案

FuncAnimation 是一个类,而不是一个函数。您确实需要保留对类实例的引用,以防止它被垃圾收集。

这也是animation documentation中的第一句话之一。

In both cases it is critical to keep a reference to the instance object. The animation is advanced by a timer (typically from the host GUI framework) which the Animation object holds the only reference to. If you do not hold a reference to the Animation object, it (and hence the timers), will be garbage collected which will stop the animation.

关于python - 为什么保存未使用的变量会产生影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48825016/

相关文章:

Python Pyglet 鼠标事件不调用 on_draw() 也不在窗口中进行更改

python - (Python 3.5.2) 如何找到我的输入是列表中的哪一项?

python - 使用python登录网页并在浏览器中显示结果

python - SocketIO(app) 缺少必需的位置参数 'mode'

python - 在四维 matplotlib 曲面中更改 Facecolors

python - 当点击更改密码时是空白页但密码已更改django

python - Pandas : create plot

matplotlib - Gnuplot:在 Y 轴上绘制直方图

python - 如何在 matplotlib 中绘制和使用 NaN 值

python - 将pdf分成两部分