Python – Implement iteration over certain class attributes on given order

Question:

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]
Asked By: heltonbiker

||

Answers:

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.

Answered By: unutbu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.