Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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]
share|improve this question
    
What have you tried so far? –  BrenBarn Jul 8 '13 at 18:47

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
Perfect. As I suspected, it was simple, but I was sidetracked by __iter__ returning self, thus requiring implementation of __next__ method (unnecessary in this case). Also, this PEP you mention settles down a long time doubt I had. Lower-case attributes from now on, thank you twice! –  heltonbiker Jul 8 '13 at 19:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.