我正在编写一个类,我想包含可以在 Jupyter 笔记本中显示的多个小部件。这些小部件应该调用更新类参数的类方法。我连接到 ipywidget 事件的函数需要访问类实例,我想通过 self,但我不知道如何让这种通信工作。
这是一个最小的例子:
import numpy as np
import ipywidgets as widgets
class Test(object):
def __init__(self):
self.val = np.random.rand()
display(self._random_button)
_random_button = widgets.Button(
description='randomize self.val'
)
def update_random(self):
self.val = np.random.rand()
print(self.val)
def button_pressed(self):
self.update_random()
_random_button.on_click(button_pressed)
我看到button_pressed()
函数如何将 Button 实例视为self
,给出“AttributeError: 'Button' object has no attribute 'update_random'”。
有没有一种方法可以通过属于类的按钮访问类 Test 的方法,或者是否有更好的方法来构建此代码以简化这些组件之间的通信?
on_click
或observe
这里有一些类中的 Jupyter 小部件示例:https : //github.com/bloomberg/bqplot/tree/master/examples/Applications
import numpy as np
import ipywidgets as widgets
class Test(object):
def __init__(self):
self.random_button = widgets.Button(
description='randomize self.val')
self.random_button.on_click(self.button_pressed)
def update_random(self):
self.val = np.random.rand()
print(self.val)
def button_pressed(self,*args):
self.update_random()
buttonObject = Test()
# display(buttonObject.random_button) # display works but is not required if on the last line in Jupyter cell.
buttonObject.random_button # Widget to be dispalyed - must last last line in cell
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句