我在使用 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/