Python:在 class 中将函数作为参数传递

Python: passing a function as a parameter while in a class

我目前正在使用 matplotlib 的 FuncAnimation 函数并且遇到了问题。我的代码遵循与以下代码类似的逻辑

import matplotlib.animation as animation
import matplotlib.pyplot as plt

class Example:
    def __init__(self):
        self.fig = plt.figure()
    def update(self, num):
        print("This is getting called")
    def animate(self):
        ani = animation.FuncAnimation(self.fig, update, interval=100)

def main():
    obj = Example()
    obj.animate()

if __name__ == "__main__":
    main()

目前,我的代码没有打印出来 "This is getting called"。我尝试传入 self.update 而不是更新到 FuncAnimation,但无济于事。我还尝试在调用 FuncAnimation 之前编写全局更新,这也不起作用。我想知道是否有人可以帮助我。

你的 animate(self) 方法必须 return 一个元组。
您还需要显示情节。

import matplotlib.animation as animation
import matplotlib.pyplot as plt


class Example:
    def __init__(self):
        self.fig = plt.figure()

    def update(self, num):
        print(f"This is getting called {num}")
        return num,

    def animate(self):
        ani = animation.FuncAnimation(self.fig, self.update, interval=100)
        plt.show()


def main():
    obj = Example()
    obj.animate()


if __name__ == "__main__":
    main()

@ReblochonMasque 的回答是正确的,您需要使用 plt.show() 实际显示图形。

然而,您不需要 return 动画函数中的任何内容(除非您想使用 blitting,在这种情况下,您需要 return 一个 Artists 的可迭代对象blit).
而且,如果您将 FuncAnimation 设为 class 变量 (self.ani),它确保能够在任何时候调用 show(),而不仅仅是在 `animate 函数中。

import matplotlib.animation as animation
import matplotlib.pyplot as plt


class Example:
    def __init__(self):
        self.fig, self.ax = plt.subplots()

    def update(self, i):
        print("This is getting called {}".format(i))
        self.ax.plot([i,i+1],[i,i+2])

    def animate(self):
        self.ani = animation.FuncAnimation(self.fig, self.update, interval=100)


def main():
    obj = Example()
    obj.animate()
    plt.show()


if __name__ == "__main__":
    main()