python - 获取类中的ipywidget按钮以通过self访问类参数?
问题描述
我正在编写一个类,我想包含多个可以在 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' 对象没有属性 'update_random'”。
有没有一种方法可以通过属于该类的按钮访问 Test 类的方法,或者是否有更好的方法可以构建此代码以简化这些组件之间的通信?
解决方案
- 按钮小部件和 on_click 应该在 init 方法中创建(或初始化)。
- on_click 方法生成一个发送给函数的参数,但在这种情况下不需要它,所以我只是在 button_pressed 函数中放了一个 *args。
- 不需要显示调用。
- 在类中调用函数时,必须使用 self. 函数名。这包括函数调用
on_click
或observe
- 在这种情况下,您不需要在 init 函数中生成随机数。
这里有一些类中的 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
推荐阅读
- r - 如何获得插值的置信区间?
- c# - 在多页 WebForms 项目中使用 VueJS
- jsp - 如何将 ArrayList 从 sevrlet 发送到 jsp 并打印出来
- batch-file - 搜索文件夹的目录
- c++ - __builtin__FUNCTION() 是否有 MSVC 等效项?
- reactjs - 如何使用带有 react native 的 react js npm 包
- powershell - 多个通配符/域的消息跟踪日志到一个 csv
- docker - Windows Docker 中的网络存储 (SMB/CIFS)
- sql-server - ASP.NET MVC 以有限的访问权限连接到 DSN
- webpack - 放置在 Project 文件夹之外的 Webpack 捆绑文件