javascript - 将小部件对象状态存储到 ipython 内核对象实例而不是对象类
问题描述
按照有状态小部件教程,我们可以创建一个简单的 DOM 小部件。这是python代码:
import ipywidgets.widgets as widgets
from traitlets import Unicode
class HelloWidget(widgets.DOMWidget):
_view_name = Unicode('HelloView').tag(sync=True)
_view_module = Unicode('hello').tag(sync=True)
_view_module_version = Unicode('0.1.0').tag(sync=True)
value = Unicode('Hello World!').tag(sync=True)
和javascript代码:
%%javascript
require.undef('hello');
define('hello', ["@jupyter-widgets/base"], function(widgets) {
var HelloView = widgets.DOMWidgetView.extend({
render: function() {
this.el.textContent = this.model.get('value');
},
});
return {
HelloView : HelloView
};
});
这如笔记本中所宣传的那样工作:
In [1]: HelloWidget()
Out [1]: Hello World!
现在,如果我想将小部件value
状态存储到对象实例,我可以更改 python 代码,使其如下所示:
import ipywidgets.widgets as widgets
from traitlets import Unicode
class HelloWidget(widgets.DOMWidget):
_view_name = Unicode('HelloView').tag(sync=True)
_view_module = Unicode('hello').tag(sync=True)
_view_module_version = Unicode('0.1.0').tag(sync=True)
def __init__(self, s):
super().__init__()
self.value = Unicode(s).tag(sync=True)
但是,这不起作用;状态未按预期呈现到输出单元格(无输出):
In [1]: HelloWidget("Hello World!")
Out [1]:
如何才能做到这一点?
解决方案
我想通了(感觉有点傻)。
该trailets.Unicode
对象是一个描述符,因此它必须附加到类对象HelloWidget
. 所以正确的代码如下:
import ipywidgets.widgets as widgets
from traitlets import Unicode
class HelloWidget(widgets.DOMWidget):
_view_name = Unicode('HelloView').tag(sync=True)
_view_module = Unicode('hello').tag(sync=True)
_view_module_version = Unicode('0.1.0').tag(sync=True)
value = Unicode().tag(sync=True) # value is set to an empty string as placeholder
def __init__(self, s):
super().__init__()
self.value = s # initialize with a value here
推荐阅读
- sql - Oracle 将时间戳转换为日期
- python - 这里的 return -1 是什么意思?
- python - 当我返回的变量有一个与之关联的字符串时,我的函数返回 None
- sql - SQL JOIN 两个表并返回对应的like
- ios - 从 TabView、PageTabViewStyle 中动态移除标签
- php - Codeigniter setflash 数据刷新后不会清除
- sql - 每当有插入时触发更新表
- python - 将 2d numpy 数组拆分为两个 1d 数组的最简单方法?
- ruby-on-rails - Searchkick::ImportError in Devise::SessionsController#destroy
- python-webbrowser - 如何通过python-3中指定的默认浏览器打开一个url?