poros
10/5/2015 - 12:33 AM

Make something iterable

Make something iterable

class RoutingTable(object):
    def __init__(self, crappy_rt):
        self.crappy_rt = crappy_rt
    
    def __len__(self):
        return self.crappy_rt.getSize()
    
    def __getitem__(self, index):
        if index >= len(self):
            raise IndexError
        return self.crappy_rt.getRouteByIndex(index)
    

# USAGE
rt = RoutingTable(crappy_rt)
for route in rt:
    ...

first_route = rt[0]


# INSTEAD OF
for rt_offset in range(rt.getSize()):
    route = rt[rt_offset]
    ...

first_route = rt.getRouteByIndex(0)