简体   繁体   中英

Python - TypeError: object of type '…' has no len()

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()

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]

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM