【问题标题】:Python: passing a function as a parameter while in a classPython:在类中将函数作为参数传递
【发布时间】:2018-06-20 03:31:12
【问题描述】:

我目前正在使用 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()

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

【问题讨论】:

    标签: python class matplotlib parameters rules


    【解决方案1】:

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

    但是,您不需要从动画函数返回任何内容(除非您想使用 blitting,在这种情况下,您需要将 Artists 的可迭代对象返回到 blit)。
    此外,如果您将 FuncAnimation 设为类变量 (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()
    

    【讨论】:

      【解决方案2】:

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

      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()
      

      【讨论】:

      • 在这种情况下,无需从update 返回任何内容。然而,返回 num 没有任何意义,要么返回 matplotlib.artist.Artists 的迭代,要么什么都不返回,但不是一些随机的东西。重点是真正展示情节。我会进一步建议将ani 设为类变量,它允许在实例方法之外调用plt.show()
      • 也许不清楚。我提供了另一个答案来说明我的意思。
      • 酷——你的答案比我的好;我赞成它,OP应该接受它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多