I am writing a class that I want to include multiple widgets that can be displayed in a Jupyter notebook. These widgets should calls class methods that update class parameters. A function that I connect to an ipywidget's events need access to the class instance, I think through self, but I can't figure out how to get this communication to work.
Here's a minimal example:
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)
I see how the button_pressed()
function sees the Button instance as self
, giving "AttributeError: 'Button' object has no attribute 'update_random'".
Is there a way that I can access methods of the class Test through a button that belongs to the class, or is there a better way that I should be structuring this code to ease communication between these components?