我正在更新一些代码以使用Dash和plotly。图形的主要代码在类中定义。我用Dash控件替换了一些Bokeh小部件,最后得到了一个如下所示的回调:
class MakeStuff:
def __init__(self, ..., **optional):
...
self.app = dash.Dash(...)
...
@self.app.callback(
dash.dependencies.Output('indicator-graphic', 'figure'),
[dash.dependencies.Input('start-time-slider', 'value'),
dash.dependencies.Input('graph-width-slider', 'value')]
)
def update_graphs(self,range_start,graph_width):
print(...)
我正在关注Dash website的一些例子。我能够运行示例,包括回调。在我的代码中,没有装饰器,代码运行没有错误,产生我预期的图形和控件。 (当然,代码不完整,但没有错误。)当我包含装饰器时,我收到此错误:
NameError:未定义名称“self”
我这样累了,首先,只是模仿代码示例:
class MakeStuff:
def __init__(self, ..., **optional):
...
app = dash.Dash(...)
...
@app.callback(
dash.dependencies.Output('indicator-graphic', 'figure'),
[dash.dependencies.Input('start-time-slider', 'value'),
dash.dependencies.Input('graph-width-slider', 'value')]
)
def update_graphs(self,range_start,graph_width):
print(...)
当然,变量“app”只能在init函数的范围内知道,所以毫无疑问,这不起作用,给出类似的错误:
NameError:未定义名称“app”
有没有一种直接的方法来设置这个装饰器工作,同时仍然保持我的代码在类定义?我猜测装饰器正在进行一些预处理,但我不太清楚它是否能够提出解决方案。
您可以将回调函数称为装饰器,如this answer所示。这应该在你的init函数中起作用:
class MakeStuff:
def __init__(self, ..., **optional):
...
self.app = dash.Dash(...)
app.callback(dash.dependencies.Output('indicator-graphic', 'figure'),
[dash.dependencies.Input('start-time-slider', 'value'),
dash.dependencies.Input('graph-width-slider', 'value')])(self.update_graphs)
...
def update_graphs(self,range_start,graph_width):
print(...)
我之前从未尝试过类实例,但没有理由不使用它。