首页 > 解决方案 > 告诉 IPython 交互小部件忽略 OOP 中的 self 参数

问题描述

我正在尝试将 IPython 交互小部件用于我的一个类中的特定方法。我希望它忽略self&colour参数,只调整i参数,但它坚持认为这self也是一个真正的参数。

这里问了一个类似的问题,但在这种情况下,这两种方法(使用fixedon self或预加载self到方法中partial)都不合适。

from ipywidgets.widgets import interact,fixed
import matplotlib.pyplot as plt

class Profile():
'''self.stages is a list of lists'''
    @interact(i=(0,5,1),colour=fixed(DEFAULT_COLOR))
    def plot_stages(self, i, colour):
        plt.plot(self.stages[i], color=colour)

这将返回一个错误: ValueError: cannot find widget or abbreviation for argument: 'self'

那么如何告诉interact忽略这一self论点呢?

标签: pythonjupyter-notebook

解决方案


定义一个接受self和 常量参数的“外部”函数。在里面定义了一个“内部”函数,它只接受交互式参数作为参数,并且可以self从外部范围访问常量参数。

from ipywidgets.widgets import interact
import matplotlib.pyplot as plt

DEFAULT_COLOR = 'r'
class Profile():
    '''self.stages is a list of lists'''
    stages = [[-1, 1, -1], [1, 2, 4], [1, 10, 100], [0, 1, 0], [1, 1, 1]]

    def plot_stages(self, colour):
        def _plot_stages(i):
            plt.plot(self.stages[i], color=colour)

        interact(_plot_stages, i=(0, 4, 1))

p = Profile()
p.plot_stages(DEFAULT_COLOR)

推荐阅读