Def 函数不适用于 plotly Python

Def function does not work with plotly Python

我正在尝试定义一个函数,但我不能调用它:

  def test():
      fig = make_subplots(rows=1, cols=2, specs=[
      [{'type': 'scatter'}, {'type': 'table'}]]
                      , shared_xaxes=True,
                      horizontal_spacing=0.05, 
                      vertical_spacing=0.05,  
                      column_widths=[0.7, 0.3])
      pass

  test()

  fig.add_trace(go.Candlestick(x=df.index,
            open=df['Open'],
            high=df['High'],
            low=df['Low'],
            close=df['Close'],
            increasing_line_color = UP_CANDLE,
            decreasing_line_color = DW_CANDLE),row=1,col=1)

当我调用它时,我检索到以下错误:NameError: name 'fig' is not defined 如果我删除该函数,代码将完美运行。

一旦你的局部变量 fig 在函数内部,函数 test 之外的任何东西都无法访问 fig 除非你从函数中 return fig - 你可以阅读scope 在 python.

我会像这样重写你的函数(pass 在你的函数中没有任何用途所以我删除了它):

def test():
    fig = make_subplots(
        rows=1, cols=2, 
        specs=[[{'type': 'scatter'}, {'type': 'table'}]], 
        shared_xaxes=True, 
        horizontal_spacing=0.05, 
        vertical_spacing=0.05,  
        column_widths=[0.7, 0.3]
    )
    return fig

然后你可以设置一个变量等于你的函数 returns:

fig = test()

然后你就可以访问`fig

.add_trace方法
fig.add_trace(go.Candlestick(x=df.index,
        open=df['Open'],
        high=df['High'],
        low=df['Low'],
        close=df['Close'],
        increasing_line_color = UP_CANDLE,
        decreasing_line_color = DW_CANDLE),row=1,col=1)