0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Dashオブジェクトをインスタンス変数にしたときの、コールバックの書き方

Last updated at Posted at 2021-10-22

Dashのソースコード量が多くなって、変数がグローバル汚染してしまうのを避けるために、Dashオブジェクトをクラス内部に保持したい場合のコールバックの書き方。

普通の書き方。

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Input(id='input_id', value=None, type='text'),
    html.Div(id='output_div')
])


@app.callback(
    Output(component_id='output_div', component_property='children'),
    [Input(component_id='input_id', component_property='value')]
)
def update_output_div(input_value):
    if input_value:
        return html.Div(className='output-area', children=[
            html.Span(input_value)
        ])
    else:
        html.Div()

クラス内部に書くやり方。


class MyDash():

    def __init__(self, app_name):
        self.app = dash.Dash(app_name)

        self.app.layout = html.Div([
            dcc.Input(id='input_id', value=None, type='text'),
            html.Div(id='output_div')
        ])

        # デコレータは使わない
        self.app.callback(
            Output(component_id='output_div', component_property='children'),
            [Input(component_id='input_id', component_property='value')]
        )(self.update_output_div)

    def update_output_div(self, input_value):
        if input_value:
            return html.Div(className='output-area', children=[
                html.Span(input_value)
            ])
        else:
            html.Div()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?