0

我想知道是否可以使输出以交互方式运行一段代码。因此,例如,如果我有一个类(伪代码中的部分):

import numpy as np

class test(object):
    def __init__():
        self.a = np.random.randn(10)
        print ## Interactive Output: Click me to view data array##

    def show():
        print a

因此,当我创建一个类实例时,它应该输出一些交互式链接(可能在 html 中)或类似的东西,当我单击它时,show()应该调用该方法。但是,我不知道如何实现这一目标。

4

1 回答 1

0

您可以使用笔记本附带的小部件(对于jupyter,它们是一个独立的包)。

这样的事情可以做你想做的事(Python 3):

from IPython.html import widgets
from IPython.display import display
import numpy as np

class Test(object):
    def __init__(self, arraylen):
        self.a = np.random.randn(arraylen)
        self.button = widgets.Button(description = 'Show')
        self.button.on_click(self.show)
        display(self.button)

    def show(self, ev = None):
        display(self.a)
        self.button.disabled = True


test = Test(10)
  • 初始化类时创建一个按钮小部件widgets.Button(description = 'Show')
  • 将事件附加到它button.on_click(self.show)
  • 并显示按钮display(self.button)
  • 在该show方法中,我包含了一种在显示数组后禁用按钮功能的方法self.button.disabled = True。如果要显示更多次数组,可以注释此行。
于 2015-08-24T06:33:10.637 回答