2014-07-03 125 views
-1

如何初始化对象实例的列表属性?我收到一个错误说初始化对象的列表属性

AttributeError: 'Particle' object has no attribute 'image' 

我尝试添加行"self.image = []"的DEF线后立即但它并没有区别同样的错误。

class Particle(object): 
    def __init__(self,data,start,finish,width): 
     for i in range(start,finish): 
      self.image = self.image.append(data[i]) 
     self.w = width 

prtlist = prtlist.append(Particle(samples,int(indices[0]),int(indices[1]),widthcount)) 

为了简洁,我没有发布所有的代码。 data是一个整数列表,start,finishwidth是整数。

编辑:

没有self.image = []宣告第一属性不存在,用它类型无的变量没有足够的功能追加。

回答

3

append返回None。在init函数的顶部,您应该初始化列表。之后,只需追加而不分配返回值。

def __init__(self,data,start,finish,width): 
     self.image = [] 
     for i in range(start,finish): 
      self.image.append(data[i]) 
     self.w = width 

查看更多Pythonic实现的其他答案。上面显示的代码通过对OP代码的最小修改简化了问题。

+0

+1为什么它没有工作 –

+1

要清楚的解释,从分配追加返回值(这是,如你所说,'None')应该不会造成一个'AttributeError的:“粒子”对象没有属性'图像'错误。如果没有'image'属性,这应该只会发生,这使得很难相信OP声称添加'self.image = []'没有改变任何东西。 – DSM

+0

@ merlin2011我现在看到了,更新OP –

3
class Particle(object): 
    def __init__(self,data,start,finish,width): 
     self.image = [data[i] for i in range(start,finish)] 
     self.w = width 
+0

为什么另一个不工作看到其他答案...基本上追加返回没有 –

+0

你的肯定是更Pythonic! :) – merlin2011