Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i don't know __iter__ in python,who can give me a good code example

my code run wrong

class a(object):
    def __iter(self):
        return 33
b={'a':'aaa','b':'bbb'}
c=a()
print b.itervalues()
print c.itervalues()

Please try to use the code, rather than text, because my English is not very good, thank you

like image 662
zjm1126 Avatar asked Dec 24 '09 04:12

zjm1126


Video Answer


1 Answers

a. Spell it right: not

   def __iter(self):

but:

   def __iter__(self):

with __ before and after iter.

b. Make the body right: not

return 33

but:

yield 33

or return iter([33])

If you return a value from __iter__, return an iterator (an iterable, as in return [33], is almost as good but not quite...); or else, yield 1+ values, making __iter__ into a generator function (so it intrinsically returns a generator iterator).

c. Call it right: not

a().itervalues()

but, e.g.:

for x in a(): print x

or

print list(a())

itervalues is a method of dict, and has nothing to do with __iter__.

If you fix all three (!) mistakes, the code works better;-).

like image 185
Alex Martelli Avatar answered Oct 10 '22 02:10

Alex Martelli