pythoniteratorgeneratoryield

Python - Implement iteration over certain class attributes on given order


I have a Position class, and it has two attributes, Lat and Lon.

I would like the following API by implementing iterator protocol (but some googling just confused me more):

pos = Position(30, 50)
print pos.Latitude
> 30

print pos.Longitude
> 50

for coord in pos:
    print coord
> 30
> 50

print list(pos)
> [30, 50]

Solution

  • You need to define an __iter__ method:

    class Position(object):
        def __init__(self, lat, lng):
            self.lat = lat
            self.lng = lng
    
        def __iter__(self):
            yield self.lat
            yield self.lng
    
    pos = Position(30, 50)
    print(pos.lat)
    # 30
    print(pos.lng)
    # 50
    for coord in pos:
        print(coord)
    # 30
    # 50
    print(list(pos))    
    # [30, 50]
    

    PS. The PEP8 style guide recommends reserving capitalized names for classes. Following the conventional will help others understand your code more easily, so I've resisted the urge to use your attribute names, and have instead replaced them with lat and lng.