【问题标题】:How do I access this variable outside the function?如何在函数外部访问此变量?
【发布时间】:2020-11-09 17:29:29
【问题描述】:

我正在尝试重新使用我在函数中定义的变量,但它一直说未定义特定变量。以后如何在函数内部使用变量斜率?或者我如何把它变成一个全局变量?

def linear_fit_detrend(data):
    slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data)
    print('slope = ',slope)
    print('intercept =', intercept)
    print('r_value =', r_value)
    print('p_value =', p_value)
    print('stnrd error =', std_err)
    detrended = data - (years_trend*slope+intercept)
    return detrended

#using function

baff_lin = linear_fit_detrend(baff_last_25)

print(slope)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-15-cec786dbdcb3> in <module>
----> 1 print(slope)

NameError: name 'slope' is not defined

【问题讨论】:

  • 不能和detrended一起退回吗?第一行中的函数返回几个变量。以它为榜样。
  • docs.python.org/3/faq/… - 返回元组是推荐的方法; global 有效,但不是首选。

标签: python function numpy jupyter


【解决方案1】:

在其他解决方案中:在全局范围内声明变量并在函数中使用它。然后就可以在函数外访问了:

slope = 0

def linear_fit_detrend(data):
    global slope
    slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data)
    print('slope = ',slope)
    print('intercept =', intercept)
    print('r_value =', r_value)
    print('p_value =', p_value)
    print('stnrd error =', std_err)
    detrended = data - (years_trend*slope+intercept)
    return detrended

# using function
baff_lin = linear_fit_detrend(baff_last_25)
print(slope)

【讨论】:

    【解决方案2】:

    尝试返回 [detrended,slope]print(baff_lin[1])

    【讨论】:

      【解决方案3】:

      另一种解决方案是让您的函数返回多个值

      def linear_fit_detrend(data):
          slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data)
          print('slope = ',slope)
          print('intercept =', intercept)
          print('r_value =', r_value)
          print('p_value =', p_value)
          print('stnrd error =', std_err)
          detrended = data - (years_trend*slope+intercept)
          return detrended, slope
      
      #using function
      
      baff_lin, slope_var = linear_fit_detrend(baff_last_25)
      
      print(slope_var)
      

      【讨论】:

        猜你喜欢
        • 2016-06-11
        • 2017-06-01
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-25
        • 2014-01-29
        • 1970-01-01
        相关资源
        最近更新 更多