调用用python生成的类时出错

2024-09-30 04:27:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个名为errors的类,在这个类中我尝试进行一些错误分析。我一直得到错误代码:

TypeError: unbound method just_print() must be called with errors instance as first argument (got ndarray instance instead)

我正在尝试使用just_print方法,以便只使用它将结果打印到解释器模块,方法是将两个数组x、y作为年份和temp传递给解释器模块

谢谢你的帮助:D

我的原始代码如下:

#imports
from pylab import *
#defining error class
class errors(object):
    #creates class object
    def __init__(self):
        pass   
    #error method
    def just_print(x,y): # defining error method
        #error analysis
        n = len(x) #length of the x data
        D = sum(x**2) - 1./n * sum(x)**2 # d is the sum of the squares minus the sum squared over n
        x_bar = mean(x) # average all x values
        p_coeff, residuals, _, _, _  = polyfit(x, y, 1, full=True) #using only the first 2 results from the poly fit returned values

        dm_squared = 1./(n-2)*residuals/D # error squared using standard forula
        dc_squared = 1./(n-2)*(D/n + x_bar**2)*residuals/D #error squared using standard forula

        dm = sqrt(dm_squared) # rooted squared error
        dc = sqrt(dc_squared) # rooted squared error

        #printing results
        print("The value for gradient is")
        print("%.3g" % p_coeff[0] , "error:" , "%.3g" % dm)
        print("The value for intercept is")
        print("%.3g" % p_coeff[1] , "error:" , "%.3g" % dc)
    return;


#reading in data from data file called wales_temp.txt
f = open("wales_temp.txt")
temps = loadtxt(f, skiprows=8)#skips thw first 8 rows as they are information aboutthe data
f.close()
years = linspace(1911,2012,(2012 - 1911 + 1), dtype=int)#set the years array of euqal length such that each corrosponds to the temp

print("The max temprature for the lest 100 years was " , "%.3g" % max(temps) , " Celcius in " , years[argmax(temps)] )
print("The min temprature for the lest 100 years was " , "%.3g" % min(temps) , " Celcius in " , years[argmin(temps)] )

print("The standard deviation of the tempratures over the past 100 years is : " , "%.3g" % std(temps))

years1990 = linspace(1990,2012,(2012 - 1990 + 1), dtype=int)
temps1990 = temps[-len(years1990):]
temps1990_9degs = temps1990[9<temps1990]
percent = (float(len(temps1990_9degs))) / (float(len(temps[9<temps])))

print("The percantage of years with tempratures above 9 degrees after 1990 compared to all the years is : " , (100*percent) ,  "%")

hist(temps, bins=len(years))
hist(temps1990 , bins = len(years))
figure("avg temps")
plot(years, temps, "bx")
best_fit = poly1d(polyfit(years,temps,1))
plot(years,best_fit(years))

test = errors
test.just_print(years, temps)

Tags: ofthedataleniserrortempjust
1条回答
网友
1楼 · 发布于 2024-09-30 04:27:29

您正在绑定到访问test.just_print(years, temps),其中test不是类的实例,请创建对象

您必须声明just_print方法staticmethod,或者将其签名更改为def just_print(self, x,y):,并用实例调用

test = errors()
test.just_print(years, temps)

相关问题 更多 >

    热门问题