Python说我的类没有调用方法

Python说我的类没有调用方法,python,class,methods,call,attributeerror,Python,Class,Methods,Call,Attributeerror,我完全卡住了。虽然我已经理解了类,但我猜我错了:/无论如何,我的代码如下所示: class LinearRegression: def __init__(self, x, y, full = 0): self.full = full self.x = x self.y = y def __call__(self): squared_sum_x = (sum(self.x))**2 n = len(self.x) xx = sum([item*

我完全卡住了。虽然我已经理解了类,但我猜我错了:/无论如何,我的代码如下所示:

class LinearRegression:

def __init__(self, x, y, full = 0):
    self.full = full
    self.x = x
    self.y = y

def __call__(self):
    squared_sum_x = (sum(self.x))**2 
    n = len(self.x)
    xx = sum([item**2 for item in self.x])
    xy = sum([xi*yi for xi, yi in zip(self.x,self.y)])
    a = 1.0*((n*xy -(sum(self.y)*sum(self.x)))/(n*xx - squared_sum_x))
    b = (sum(self.y) - a*sum(self.x))/n
    if self.full == 0:
        return (a,b)
    elif self.full == 1:
        squared_sum_y = (sum(self.y))**2
        yy = sum([item**2 for item in self.y])
        R = float((n*xy -(sum(self.y)*sum(self.x)))/(((n*xx - squared_sum_x)*(n*yy - squared_sum_y))**0.5))
        S_a = (1/(n-2))*((yy-(a*xy)-(b*sum(self.y)))/(xx-(n*xx)))
        S_b = S_a * (n*xx)
        return (a, b, R, S_a, S_b)
    else:
        return "full parameter must be 0, 1 or empty"

lr = LinearRegression(range(10),range(10,30,2),0)
lr()
我遇到以下错误:

AttributeError: LinearRegression instance has no __call__ method

问题是:为什么?因为我花了数小时分析这段代码,完全不知道出了什么问题……

我认为问题在于您的缩进。实际上,您并没有在类中包含这些方法,因为缩进将它们放在“外部”。请尝试以下方法:

class LinearRegression:

    def __init__(self, x, y, full = 0):
        self.full = full
        self.x = x
        self.y = y

    def __call__(self):
        squared_sum_x = (sum(self.x))**2 
        n = len(self.x)
        xx = sum([item**2 for item in self.x])
        xy = sum([xi*yi for xi, yi in zip(self.x,self.y)])
        a = 1.0*((n*xy -(sum(self.y)*sum(self.x)))/(n*xx - squared_sum_x))
        b = (sum(self.y) - a*sum(self.x))/n
        if self.full == 0:
            return (a,b)
        elif self.full == 1:
            squared_sum_y = (sum(self.y))**2
            yy = sum([item**2 for item in self.y])
            R = float((n*xy -(sum(self.y)*sum(self.x)))/(((n*xx - squared_sum_x)*(n*yy - squared_sum_y))**0.5))
            S_a = (1/(n-2))*((yy-(a*xy)-(b*sum(self.y)))/(xx-(n*xx)))
            S_b = S_a * (n*xx)
            return (a, b, R, S_a, S_b)
        else:
            return "full parameter must be 0, 1 or empty"

这样,方法将“在”类中,而不是独立定义的函数。

格式正确吗?正如您肯定知道的,缩进在Python中很重要。
dir(LinearRegression)
显示的是类的一部分吗?您可能有缩进问题。谢谢,这确实是格式问题,init缩进严重。我之前没有检查它,因为它是我的老师编写的这门课原型的一部分——假设是一个拥有博士学位的人。在计算机科学中不会犯这样的错误,我猜我错了:PAs发布后,你的类也不会有
\uuuu init\uuuu
。请修正缩进以准确显示您正在运行的代码。缩进这两个方法后,对我有效--结果
(2.0,10.0)
。但是,如果不这样做,我会得到一个
IndentationError:在
def\uu init\uz():
行上应该有一个缩进块,您也应该得到它`如果OP是一个直接副本,解释器会抱怨一个空类(
IndentationError:应该是一个缩进块
)。所以我认为这不是唯一的原因。