获取类中的 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' object has no attribute 'update_random'”。

有没有一种方法可以通过属于类的按钮访问类 Test 的方法,或者是否有更好的方法来构建此代码以简化这些组件之间的通信?

道格
  1. 按钮小部件和 on_click 应该在 init 方法中创建(或初始化)。
  2. on_click 方法生成一个发送到函数的参数,但在这种情况下不需要它,所以我只是在 button_pressed 函数中放置了一个 *args。
  3. 不需要显示调用。
  4. 在类中调用函数时,必须使用 self. 函数名这包括函数调用on_clickobserve
  5. 在这种情况下,您不需要在 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

通过Java中的参数访问类的内容?

如何在ipywidget按钮中显示全文?

在类中获取指向 self 的指针

self.variable.function() 在 python 中的含义或通过类自变量访问方法

通过类创建按钮

在 Python 中进行多处理时,在类实例中通过 self 传递参数

尝试访问其他类中的方法时,PyCharm中出现“参数” self”未填充”错误

在父类的self中访问匿名类的名称。

通过函数参数从向量中获取类指针

通过骆驼进行Yaml序列化:使用基类加载/转储并访问装饰器中的type(self)

通过 C++ 函数对象类访问参数

如何从python类函数访问对self的调用

如何通过使用 jquery 引用其类名来从单击的单选按钮中获取值?

如何访问在类<< self中定义的实例变量

类方法中定义的python函数可以访问self吗?

从python中的另一个类访问self

在目标c中访问类方法。使用的是self还是classname?

swift类作为不带.self的参数

在类方法参数中未定义self

单击按钮时如何通过类名获取同级元素?

获取每个 div 并通过单击按钮更改类

使用参数访问类

通过Shapeless获取默认的case类参数

在没有 self 的函数的类的 ruby 中如何获取当前类名?

如何在__init__中获取当前的Python类名,而不管“ self”的类如何?

通过继承类中的声明获取当前类

如何通过owlapi中的域类获取objectProperty的范围类?

通过变量访问类

保留多个ipywidget中的订单