Python - TypeError: object of type '…' has

2019-06-23 02:17发布

Here is a class:

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

This is a part of my program:

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)

But I'm geting an error at "cr12 = cr.weave(cr2)":

for i in range(min(length, len(other))):

TypeError: object of type 'CoordinateRow' has no len()

3条回答
孤傲高冷的网名
2楼-- · 2019-06-23 03:03

Iterating over a range of len(something) is very much an anti-pattern in Python. You should be iterating over the contents of the containers themselves.

In your case, you can just zip the lists together and iterate over that:

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
查看更多
smile是对你的礼貌
3楼-- · 2019-06-23 03:17

other is of type CoordinateRow, which does not have a length. Use len(other.coordinate_row) instead. This is the list that does have the length property.

查看更多
看我几分像从前
4楼-- · 2019-06-23 03:20

You need to add a __len__ method, then you can use len(self) and 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]
查看更多
登录 后发表回答