2014-11-23 109 views
2

这里是一个类:的Python - 类型错误:类型的 '...' 对象没有LEN()

class CoordinateRow(object): 

def __init__(self): 
    self.coordinate_row = [] 

def add(self, input): 
    self.coordinate_row.append(input) 

def weave(self, other): 
    result = CoordinateRow() 
    length = len(self.coordinate_row) 
    for i in range(min(length, len(other))): 
     result.add(self.coordinate_row[i]) 
     result.add(other.coordinate_row[i]) 
    return result 

这是我计划的一部分:

def verwerk_regel(regel): 
cr = CoordinateRow() 
coordinaten = regel.split() 
for coordinaat in coordinaten: 
    verwerkt_coordinaat = verwerk_coordinaat(coordinaat) 
    cr.add(verwerkt_coordinaat) 
cr2 = CoordinateRow() 
cr12 = cr.weave(cr2) 
print cr12 

def verwerk_coordinaat(coordinaat): 
coordinaat = coordinaat.split(",") 
x = coordinaat[0] 
y = coordinaat[1] 
nieuw_coordinaat = Coordinate(x) 
adjusted_x = nieuw_coordinaat.pas_x_aan() 
return str(adjusted_x) + ',' + str(y) 

但我米在 “CR12 = cr.weave(CR 2)” 歌厅一个错误:在范围

对于i(分钟(长度,LEN(其他))):

类型错误:类型的对象 'CoordinateRow' 没有升en()

+0

不知道你的问题是什么。你在'CoordinateRow'的实例上调用'len',但该类没有定义'__len__'函数。 – 2014-11-23 13:57:50

回答

0

other是类型CoordinateRow,它没有长度。改为使用len(other.coordinate_row)。这是具有长度属性的列表。

3

您需要添加一个__len__方法,那么你可以使用len(self)len(other)

class CoordinateRow(object): 
    def __init__(self): 
     self.coordinate_row = [] 

    def add(self, input): 
     self.coordinate_row.append(input) 

    def __len__(self): 
     return len(self.coordinate_row) 

    def weave(self, other): 
     result = CoordinateRow() 
     for i in range(min(len(self), len(other))): 
      result.add(self.coordinate_row[i]) 
      result.add(other.coordinate_row[i]) 
     return result 
In [10]: c = CoordinateRow()  
In [11]: c.coordinate_row += [1,2,3,4,5]  
In [12]: otherc = CoordinateRow()  
In [13]: otherc.coordinate_row += [4,5,6,7]  
In [14]:c.weave(otherc).coordinate_row 
[1, 4, 2, 5, 3, 6, 4, 7] 
+0

我试过你的方法,但它给错误如下:TypeError:'NoneType'对象不可迭代 – 2016-03-21 06:50:46

2

迭代一个范围LEN(东西)的非常多了一个Python反模式。你应该迭代容器本身的内容。

在你的情况,你可以只是压缩列表在一起,迭代是:

def weave(self, other): 
    result = CoordinateRow() 
    for a, b in zip(self.coordinate_row, other.coordinate_row): 
     result.add(a) 
     result.add(b) 
    return result 
相关问题