【问题标题】:Telling IPython interact widget to ignore self argument in OOP告诉 IPython 交互小部件忽略 OOP 中的 self 参数
【发布时间】:2019-06-12 17:07:38
【问题描述】:

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

here 提出了类似的问题,但在这种情况下,这两种方法(在 self 上使用 fixed 或将 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 参数?

【问题讨论】:

  • " 但它坚持认为 self 也是一个真正的论点。"没错。
  • 那么如何解决这个问题@juanpa.arrivillaga
  • 我也遇到了同样的问题,有人找到答案了吗?

标签: python jupyter-notebook


【解决方案1】:

定义一个接受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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2011-06-20
    • 2015-11-01
    • 2015-08-04
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    相关资源
    最近更新 更多