如何在函数外部访问此变量?

时间:2020-11-09 17:29:29

标签: python function numpy jupyter

我试图重用我在函数中定义的变量,但一直说未定义特定变量。以后如何在函数内使用变量斜率?或者如何将其变成全局变量?

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

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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

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)

答案 2 :(得分:0)

尝试返回model <- lm(y ~ a:b + a + b + c) linearHypothesis(model,matchCoefs(model,":"))